Fabric.js is a library designed to simplify the writing of Canvas programs. Canvas is a good Canvas capability provided by browsers for HTML5, but the Api is not friendly and cumbersome to use. Drawing simple graphics at work is actually ok. If you do some complex graphics drawing, writing some complex effects, and logic is not so convenient. Fabric.js was developed for this purpose, using canvas primarily as an object.
Install the Fabric package and reference it in the project
Command line to install fabric.js
npm install fabric –save
Introduce into the project
import { fabric } from ‘fabric’;
Simple shape drawing
// Declare canvas
var canvas =new fabric.Canvas('main');
// Draw a square
var rect = new fabric.Rect({
left:10.// The distance to the left
top:10.// The distance from the top
fill:'# 000'.// Fill the color
width:20./ / width
height:20 / / height
});
// Add the drawn graph to the canvas
canvas.add(rect);
Copy the code
- Square var rect = new fabric.rect
- Circle var circle = new fabric.circle
- Var triangle = new fabric.triangle
Manipulate and draw pictures
- 1. Get img from HTML and insert it
<body> <canvas id="canvas" width='300' height='300'></canvas> <img src="img.png" id="img"> </body> <script> var canvas = new fabric.Canvas('canvas'); var imgElement = document.getElementById('img'); var canvasImg = new fabric.Image(imgElement,{ left:10, top:10, width:20, height:10, }); canvas.add(canvasImg); // Add canvas </script>Copy the code
- Js directly inserts the image
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('img.png'.function(oImg) {
canvas.add(oImg);
});
Copy the code
Event listeners
- 1. Canvas Canvas event
// Listen for events when the mouse is pressed on the canvas
var canvas = new fabric.Canvas('canvas');
canvas.on('mouse:down'.function(e) {
console.log(e);
})
// mouse:down: when the mouse is pressed down
// mouse:move: when the mouse moves
// mouse:up: when the mouse is up
Copy the code
- 2. Events for objects on the canvas
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({ width: 10.height: 10.fill: '# 000000' });
rect.on('selected'.function() {// Select the listening event
});
// After :render :render
// object:selected: Selected
// Object :moving: move
// object:rotating
// object:added :added
// object:removed
Copy the code
Serialization and deserialization
- 1. Serialization (Convert canvas drawn graph into a fabric to deserialize available JSON data)
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 10.height: 10.fill: '# 000000'
});
canvas.add(rect);
console.log(canvas.toJSON());
Copy the code
- 2. Deserialize
var canvas = new fabric.Canvas('canvas');
canvas.loadFromJSON('{"objects":[{"type":"rect","left":0,"top":0,"width":10,"height":10,"fill":"#000000","overlayFill":null}')
Copy the code