Reprint please retain this part of the content, indicate the source. Pay attention to the public number “number one front-end”, weekly fresh front-end good news push.

In addition, the front end team of Toutiao is looking forward to your joining us

Introduction to the

Fabricjs is not particularly well known at home, but it should be particularly popular abroad. It is a powerful JS library, using it can be very convenient to operate canvas. Usually, when using Canvas, I always need to learn its VARIOUS APIS and be skilled in drawing simple graphics. Once it gets a little complicated, I need to constantly check documents, which is very inconvenient. Fabric.js provides the ability to create elements on it, edit graphics and text, serialize and deserialize SVG and JSON formats, respond to events on elements, and more. Fabricjs is a completely open source project, licensed by THE Massachusetts Institute of Technology, that has been glowing for years.

The overall structure

use

npm install fabric
Copy the code
< script SRC = "http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js" > < / script >Copy the code

The object operation

There is a canvas element in the body of the HTML. Get the fabric object: var canvas = new fabric.canvas (‘main’);

<canvas width="800" height="800" id="main"></canvas>
Copy the code

A simple graphical

Draw a rectangle on canvas:

var rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: '#f0f',
    width: 30,
    height: 30
})
canvas.add(rect);
Copy the code

If the rectangle was created using the native Canvas API, it would look like this:

var ele = document.getElementById('main');
var ctx = canvasEl.getContext('2d');
ctx.fillStyle = '#f0f';
ctx.fillRect(100, 100, 30, 30);
Copy the code

Fabric can be graphically objectized and can operate on the object later. If you want to get properties of rect, just rect.get(“), or if you want to add other properties, We can use rect.set. If we want to remove the rect from the canvas, we just need canvas.remove(rect). Draw circles on canvas:

var circle = new fabric.Circle({
    radius: 50,
    fill: "#fcb",
    left: 200,
    top: 100,
})
Copy the code

Draw a triangle on canvas:

var trigle = new fabric.Triangle({
    fill: "#fcb",
    left: 300,
    top: 100,
    height: 100,
    width: 80,
})
Copy the code

The picture

var imgEle = document.getElementById('img-d2');
var imgInstance = new fabric.Image(imgEle, {
    left: 100,
    top: 100,
    width: 200,
    height: 200,
    angle: 30
})
canvas.add(imgInstance);
Copy the code

The img element is fine if it is used for display on a page, but if it is only used to add image material to the fabric, adding such an img element is a bit redundant. Fabric also provides methods for creating picture objects based on urls:

fabric.Image.fromURL('./d2.png', function(img){ console.log(img); / / img. Scale (0.5); canvas.add(img); }, {left: 100, top: 100, width: 200, height: 200, Angle: 30})Copy the code

After creating the image, you can also manipulate the image object. Normally, we use the image as a background or to highlight a display effect

canvas.setBackgroundImage('./d2.png', canvas.renderAll.bind(canvas));
Copy the code

You can also use multiple images as a background, based on the code above:

canvas.setOverlayImage('.. /assets/d1.png', canvas.renderAll.bind(canvas));Copy the code

Display effect: Apply a filter to the image:

The original imageCopy the code
/ / add filter, filter effects is an array, you can add multiple img. Filters. Push (new fabric. The Image. The filters. The Grayscale (), the new fabric. The Image. The filters. The Invert ()); Img. applyFilters(img.filters); // Apply the filter and re-render the canvas.Copy the code

Filter effect pictureCopy the code

More filters can be found in the documentation, and effects such as scaling and rotation of the image object can be obtained by setting its properties, such as img.set(‘ Angle ‘, 60).

Irregular figure

Drawing irregular shapes on canvas:

var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({
    left: 120,
    top: 120,
    fill: "#4040fe"
})
Copy the code

For drawing irregular paths or graphics on canvas, “M” stands for the “move” command, which in this case means from0, 0The beginning. “L” stands for “straight line”. Let the pen draw a straight line to200100. Another “L” creates a to177200The line “z” instructs the plotter to close the current path and finally determine the shape. It can also use set to set its other properties for more effects:Path. set({fill: 'red', stroke: 'green', opacity: 0.5});

In addition to the M and L and so on up here, you can call it C, and C is the Bezier curve, Its role is to draw the curve of the var path = new fabric. The path (‘ M 0 0, 200, 100 L, 170 L, 200 C36.67, 0,29.5, 3.22, 24.31, 8.41 Z ‘); However, it is very difficult to get the desired irregularity by setting points yourself. Fabric provides an alternative to this implementation by loading SVG, loadSVGFromString or loadSVGFromURL methods to load an SVG file and let Fabric’s SVG parser iterate over all SVG elements and create the appropriate Path object.

fabric.loadSVGFromURL('./tab.svg', function(objects){
    var SVG = fabric.util.groupSVGElements(objects);
    canvas.add(SVG).centerObject(SVG).renderAll();
    SVG.setCoords();
})
Copy the code

color

Fabric provides a convenient way to create colors that can be used to create graphics:

var col1 = new fabric.Color('#f55'); var col2 = new fabric.Color('#123123'); var col3 = new fabric.Color('356735'); Var col4 = new fabric.color (' RGB (100,0,100)'); Var col5 = new fabric.color ('rgba(10, 20, 30, 0.5)');Copy the code

RGB and HEX values can be converted to each other:

col1.toRgb()
col4.toHex()
Copy the code

Var colo5 = col2. OverlayWith (col3); If col2 does this, not only will it get a new color col5, col2 will also be overwritten. Conversion: col2.tograyscale () converts toGrayscale color. Other transformations can be found in API. Color application:

Rect({left: 100, top: 100, width: 100, height: 100, fill: Rect. setGradient('fill',{x1: 0, y1: 0, x2: circle. Width, y2: 0, colorStops:{0: col1.toRgb(), 1: col3.roRgb() } })Copy the code

animation

You can set the properties of a graphical object using set. If you want to animate the properties, you can specify the properties.

Rect.animate ('left', "500", {// Set the offset from the left side 500 onChange: canvas. Renderall. bind(canvas), duration: 2000, easing: Fabric. Util. Ease. EaseInOutBounce / / animation})Copy the code

Instead of calculating the final value of the animation, you can use the += -= calculation symbol

Rect.animate ('left', "+=500", {// Set the distance relative to the current left offset by 500 onChange: canvas.renderall. bind(canvas), duration: 2000, easing: Fabric. Util. Ease. EaseInOutBounce / / animation})Copy the code

The third argument to the animate function includes the following properties:

  • From: Allows you to specify the starting value of the animation property if we do not want to use the current value.

  • Duration: indicates the animation duration

  • OnComplete: Callback function on completion

  • OnChange: function to be called when a value changes

  • Easing: Animates the changing curve

The text

Fabric not only manipulates text in the form of objects, but also provides more functionality to manipulate text than canvas does:

Support multi-line input, text alignment selection, text background Settings, text decoration, text line height, set word spacing, modify styles, rich text (support tags), input editing in canvas. There are two common ways to create text, and their parameters: the first parameter is the text content, and the second is the text property object

Var TXT = new fabric.Text('aker', {left: 140, // position top: 140, shadow: 'rgba(0,0,0,0.3) 15px 15px 15px', // shadow fontFamily: 'Hoefler Text', // stroke: '#ff1318', // brush for strokeWidth: Fill: '#0f0', // fill color fontSize: 60, // fontSize}); var tex = new fabric.IText('click',{left:100,top:400, minWidth: 50}); // Inherit from Text, implement setting focus, editableCopy the code

The manipulation properties of the text are very similar to those in CSS, and you can also set the background color of the text and so on. TextDecoration, fontStyle, textAlign, textBackgroundColor, lineHeight, etc

combination

Fabric also provides a method for combining created objects. By combining several objects into a new object, we can operate on it:

var canvas = new fabric.Canvas('main');
var circle = new fabric.Circle({
    radius: 100,
    fill: '#eef',
    scaleY: 0.5,
    originX: 'center',
    originY: 'center'
});
var text = new fabric.Text('hello world', {
    fontSize: 30,
    originX: 'center',
    originY: 'center'
});
var group = new fabric.Group([ circle, text ], {
    left: 150,
    top: 100,
    angle: -10
});
canvas.add(group);
Copy the code

renderingCopy the code

If the position of each element is not set when creating the object, the default position is to place the object in the center of the group after the combination. If you need to set the position of the object in the combination, you can set the position during the creation of the object, for example:

var circle3 = new fabric.Circle({
    radius: 50,
    fill: 'blue',
    left: 200
});
Copy the code

A group can be thought of as a small canvas because it is similar to the canvas operation object. After the group is created, you can perform operations on the added objects:

group.item(0).set('fill', 'red');
group.item(1).set({
  text: 'trololo',
  fill: 'white'
});
Copy the code

Another common way to manipulate items is: size() indicates the number of all objects in a group. Contains () allows you to check if a particular object is in a group. Add adds an object, remove removes an object, and addWithUpdate adds an object to the center of the group and updates the group’s properties.

The event

Fabric provides methods not only to create objects, but also to listen for events on created objects. A demo of mouse movement events is also provided on the Fabric website. Fabric event listening is similar to event handling in JQ. Here is a demo of Fabric listening for mouse click events:

var canvas = new fabric.Canvas('main'); canvas.on('mouse:down', function(options) { console.log(options.e.clientX, options.e.clientY); If (options.target) {// Add point on layer object console.log('an object was clicked! ', options.target.type); }}); var rect = new fabric.Rect({ left: 100, top: 100, fill: '#f0f', width: 30, height: 30 }); canvas.add(rect);Copy the code

The outputCopy the code

Fabric provides fewer events, but it is much more convenient than writing native ones.

  • Mouse response events: “mouse: Down “, “mouse: Move “, and “mouse: Up “.

  • General event: “After :render”

  • Select the events: “Before: Selection :cleared”,” Selection :created”, “Selection :cleared”.

  • Object events: “object:modified”, “object:selected”, “object:moving”, “object:scaling”, “object:rotating”, “object:added”, and “object:removed”

The official documentation has special remarks for “Object: Moving” and “Object: Scaling”. These two events are very sensitive and will respond even if only 1px changes. Therefore, anti-shaking should be added if these two events are used. The use of these events should be suitable for many scenarios, such as saving the canvas, listening for object: Modified, and saving it if it happens, so that changes are not lost. The first three types of events are on the canvas, which can be obtained by using the options parameter. The following object events can also be used for layer objects.

rect.on('selected', function() { console.log('selected a rectangle'); }); .Copy the code

The result of my experiment is that the above object does not respond to the on event (probably due to usage issues).

serialization

It is not enough for an application to simply provide a way to operate on it, otherwise it will become a purely presentation application, and it needs to provide a way to save or extract data. Fabric provides good serialization and deserialization methods for storing data as JSON, base64 images, SVG, object, and toString.

var canvas = new fabric.Canvas('main');
console.log(canvas.toString())
Copy the code

We have toString methods for all canvas objects, and we can also create objects for toString overwriting.

For toString, the output is simple and the object details are not intuitive, we can use toObject or toJson (both are similar) :

console.log(rect.toObject())
console.log(rect.toJSON())
console.log(rect.toString())

Copy the code

If you expand the output, you can see that the default value for unset attributes is 0 or NULL.

Note for deserialization that loadFromJSON corresponds to toJSON and loadFormDatalessJSON corresponds to toDatalessJSON. However, for performance reasons, not all attributes can be serialized. Fabric only wraps some commonly used attributes, so if you set some less-used attributes, you need to modify the image attributes when loading JSON data. More on serialization can be found in the documentation.

experience

Picture editor

data

Fabricjs.com/articles/ www.321332211.com/thread?topi…

Note: write some demo, have interest to play