What is the fabric. Js
Fabric.js is a library that encapsulates the Canvas API. Like most canvas libraries on the market, fabric.js supports many effects
Why
First let’s take a look at the current comparison of the major librariesOf course, Three. js dominates the star list by an absolute margin, and it is believed that most of the front-end users have used it.
But their priorities are different.
Fabric.js provides an interactive object model for the Canvas element, and Fabric also has an SVG-to-Canvas (and canvas to SVG) parser. With fabric.js, you can create and populate objects on a canvas. Objects like simple geometric shapes. While Three. js focuses more on 3D and texture.
If you’re looking for a Canas library that supports Node-Canvas, or interactive object model, congratulations!
How
contrast
Fabric.js is easy to get started with if you need to draw a square on a canvas:
const canvas = document.queryselector('#canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
/ / draw a rectangle
ctx.fillRect(100.100.20.20);
Copy the code
While the use of the fabric. Js
const canvas = new fabric.Canvas('canvas');
const rect = new fabric.Rect({
left: 100.top: 100.fill: 'red'.width: 20.height: 20
});
canvas.add(rect);
Copy the code
It is obvious here that fabric.js draws a red-filled rectangle based on an object.
One might ask here: Why do I think these two options are similar? Don’t worry, this is just a basic comparison, we now want to draw a more complex rectangle with a border, an Angle, and a drag:
const canvas = new fabric.Canvas('canvas');
const rect = new fabric.Rect({
left: 100.top: 100.fill: 'red'.width: 20.height: 20.angle:20.lockMovementX:false.lockMovementY:false.evented:true.stroke: "rgba(255, 255, 255, 1)".strokeWidth: 2
});
canvas.add(rect);
Copy the code
How about, just add the corresponding value to its object property in new Fabric.rect, and the canvas is guaranteed to be rendered and can be dragged, scaled, and rotated at will.
Fabric.js object type
- Image: indicates the image type
- Textbox: Text type
- The rect: rectangle
- Circle, circle
- Group: a group of
- path: svg
- Polygon: polygon
- Line: line
- …
Fabric.js supports several types, including the official documentation
conclusion
Well, that’s it for today, and we’ll pick it up next time