This is the second day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Introduction:

When we want to draw a basic simple shape on the Canvas, we don’t have to worry about using Canvas. But when any kind of interaction is needed on the canvas, drawing complex graphics and changing images for specific situations, it becomes difficult to use the native Canvas API. Fabric aims to solve this problem.

Fabric provides an interactive object model on top of the canvas elements. Fabric also has an SVG-to-Canvas (and Canad-to-SVG) parser

For convenience, I'll show you how to use Fabric through the Vue projectCopy the code

A, install,

yarn add fabric -S
#or
npm i fabric -S
Copy the code

You can also download the latest JS file from the official website and introduce it through the script tag

Second, the use of

<! -- html -->
<canvas id="canvas" width="500" height="500"></canvas>
Copy the code

2.1 Draw a simple graph

Fabric provides seven basic shapes:

  • Fabric. Circle (round)
  • Fabric.Ellipse
  • Fabric. The Line (Line)
  • Fabric.Polyline (multiple lines drawn into a graph)
  • Fabric. Triangle
  • Fabric.Rect
  • Fabric.Polygon
  • rectangular
// js

/ / into the fabric
import { fabric } from "fabric";

// Create a Fabric instance
let canvas = new fabric.Canvas("canvas"); // You can zoom out and rotate with the mouse
// or
// let canvas = new fabric.StaticCanvas("canvas"); // Fabric object with no mouse interaction

// Create a rectangle object
let rect = new fabric.Rect({
    left: 200.// The distance to the left
    top: 200.// The distance from the top
    fill: "green".// Fill the color
    width: 200.// The width of the rectangle
    height: 200.// The height of the rectangle
});

// Add the rectangle to the canvas
canvas.add(rect);
Copy the code

You can see that the interface is filled with a green rectangle that can be zoomed in and out with the mouse and rotated to configure element styles in the form of objects, very convenient!

  • Circles and triangles
// Create a circular object
let circle = new fabric.Circle({
    left: 0.// The distance to the left
    top: 0.// The distance from the top
    fill: "red".// Fill the color
    radius: 50.// The radius of the circle
});
// Create a triangle object
let triangle = new fabric.Triangle({
    left: 200.// The distance to the left
    top: 0.// The distance from the top
    fill: "blue".// Fill the color
    width: 100./ / width
    height: 100./ / height
});
// Add the shape to the canvas
canvas.add(circle, triangle);
Copy the code

We can determine whether we can interact with related elements by setting the following properties

canvas.selection = false; // Disable all selections
rect.set("selectable".false); // Just disable the selection of the rectangle
Copy the code

2.2 Drawing pictures

There are mainly two ways to draw by URL and IMG tag

// Draw the image through the URL
fabric.Image.fromURL(
    // require("./xxx.jpeg")
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.thaihot.com.cn%2Fuploadimg%2Fico%2F2021%2F0711%2F162598253573 9193. jpg&refer=http%3a%2f%2fimg.thaihot.com.cn&app=2002&size=f9999, 10000 & q = a80 & n = 0 & g = 0 n & FMT = jpeg? = 1630940858 & t = e1d24f the SEC f0a7eaeea2ff89cedf656a9374".(img) = > {
        img.scale(0.5); canvas.add(img); });// It can also be drawn by a label
let img = document.getElementById("img");
let image = new fabric.Image(img, {
    left: 100.top: 100.opacity: 0.8}); canvas.add(image);Copy the code

2.3 Drawing using a user-defined path

To do that we need to understand what a few parameters mean

  • M: “move” to a certain point
  • L: “line” x,y
  • C: “curve”
  • A: “arc” arc
  • Z: closed path (similar to create selection in PS)
let customPath = new fabric.Path("M 0 0 L 300 100 L 170 100 z");
customPath.set({
    left: 100.top: 100.fill: "green"}); canvas.add(customPath);Copy the code

let customPath = new fabric.Path(
    "M 0 0, 300, 100 L, 170 L, 100 L 70 300 L 200 C136.19 20, 2.98, 128.98, 0121.32, 0 z"
);
Copy the code

As you can see, with path drawing, we can make very complex graphics (but we usually don’t, we usually use it to parse SVG and get path to restore graphics).

2.4 the animation

The first argument is the property of the animation, the second is the final position of the animation, and the third is an optional object that specifies the details of the animation: duration, callbacks, motion effects, and so on.

The third parameter mainly has

  • Duration the default value is 500ms. Can be used to change the duration of the animation.
  • From allows you to specify the starting value of the animation property (if we do not want to use the current value).
  • Callback after the onComplete animation has finished.
  • The easing kinetic function.

2.41 Absolute animation

let canvas = new fabric.Canvas("canvas");
let rect = new fabric.Rect({
    left: 400.// The distance to the left
    top: 200.// The distance from the top
    fill: "green".// Fill the color
    width: 200./ / width
    height: 200./ / height
});
rect.animate("left".100, {
    onChange: canvas.renderAll.bind(canvas),
    duration: 1000}); canvas.add(rect);Copy the code

2.42 Relative animation (the second parameter determines the final effect of the animation by +=,-=, etc.)

rect.animate("left"."+ = 100", {
    onChange: canvas.renderAll.bind(canvas),
    duration: 1000});Copy the code

rect.set({ angle: 45 });
rect.animate("angle".- = "90", {
onChange: canvas.renderAll.bind(canvas),
duration: 2000});Copy the code

2.43 Define the action function of the animation

By default, the animation is executed using the “easeInSine” action. If that’s not what you need, Fabric gives us a lot of built-in animation, with a bunch of action options under fabric. Util. Ease. Commonly used with easeOutBounce, easeInCubic easeOutCubic, easeInElastic, easeOutElastic, easeInBounce and easeOutExpo, etc

rect.animate("left".100, {
    onChange: canvas.renderAll.bind(canvas),
    duration: 1000.easing: fabric.util.ease.easeOutBounce,
});
Copy the code

2.5 Image Filters

Fabric currently provides us with the following built-in filters

  • BaseFilter Basic filter
  • The Blur Blur
  • Brightness Brightness
  • ColorMatrix ColorMatrix
  • Contrast Contrast
  • Convolute convolution
  • Gamma Gamma
  • Grayscale gray
  • HueRotation
  • Invert the horse
  • Noise Noise
  • Pixelate pixelated
  • RemoveColor removes the color
  • Resize Adjusts the size
  • Saturation saturated

2.51 Single filter

fabric.Image.fromURL(require("./aaa.jpeg"), (img) = > {
    img.scale(0.5);
    canvas.add(img);
});
fabric.Image.fromURL(require("./aaa.jpeg"), (img) = > {
    img.scale(0.5);
    // Add a filter
    img.filters.push(new fabric.Image.filters.Grayscale());
    // After the image is loaded, apply the filter effect
    img.applyFilters();
    img.set({
        left: 300.top: 250}); canvas.add(img); });Copy the code

2.52 Overlay filter

The “filters” attribute is an array, and we can use the array method to do anything we want: remove filters (pop, splice, shift), add filters (push, unshift, splice), and even combine multiple filters. When we call applyFilters, any filters that are present in the array of “filters” will be applied one by one, so let’s try to create an image that is both color neutral and Brightness.

fabric.Image.fromURL(require("./aaa.jpeg"), (img) = > {
    img.scale(0.5);
    // Add a filter
    img.filters.push(
        new fabric.Image.filters.Grayscale(),
        new fabric.Image.filters.Sepia(), / / color
        new fabric.Image.filters.Brightness({ brightness: 0.2 }) / / brightness
    );
    // After the image is loaded, apply the filter effect
    img.applyFilters();
    img.set({
        left: 300.top: 250}); canvas.add(img); });Copy the code

Fabric also supports custom filters. I will update Fabric Advanced after this post has received 500 likes. Thanks for your support

2.6 color

Whether you’re using hexadecimal, RGB, or RGBA colors, Fabric handles it just fine

2.61 Defining a color

new fabric.Color("#f55");
new fabric.Color("#aa3123");
new fabric.Color("356333");
new fabric.Color("RGB (100,50,100)");
new fabric.Color("Rgba (100, 200, 30, 0.5)");
Copy the code

2.62 Color conversion

new fabric.Color('#f55').toRgb(); RGB (255,85,85) "/ /"
new fabric.Color('RGB (100100100).).toHex(); / / "646464"
new fabric.Color('fff').toHex(); // "FFFFFF"
Copy the code

We can also overlay it with another color, or convert it to a grayscale version.

let redish = new fabric.Color("#f55");
let greenish = new fabric.Color("#5f5");
redish.overlayWith(greenish).toHex(); // "AAAA55"
redish.toGrayscale().toHex(); // "A1A1A1"
Copy the code

2.7 the gradient

Fabric supports gradients through the setGradient method, defined on all objects. Call setGradient(‘fill’, {… }) like setting the “fill” value of an object.

let circle = new fabric.Circle({
  left: 100.top: 100.radius: 50
});

circle.setGradient("fill", {
    // The starting position of the gradient
    x1: 0.y1: 0.// The position where the gradient ends
    x2: circle.width,
    y2: 0.// The gradient color
    colorStops: {
        // The gradient ranges from 0 to 1 (0,0.1,0.3,0.5,0.75,1)
        0: "red".0.2: "orange".0.4: "yellow".0.6: "green".0.8: "blue".1: "purple"}});Copy the code

2.8 the text

The fabric.Text object provides more functionality for Text than canvas, including:

  • Unfortunately, the native text method ignores creating a new line.
  • Text alignment Left, center, and right. This is useful when using multiple lines of text.
  • The background also supports Text alignment.
  • Underline, underline, cross line.
  • Line Height is useful when using multiple lines of text.
  • Make text more compact or spaced.
  • Subscope Subranges applies colors and properties to the subobjects of a text object.
  • Multibyte supports emojis.
  • You can type text directly On the canvas.
let text = new fabric.Text(
    "Hello, everyone! This is Qian Pu zhai, N I am Rong Ding, a man who wants to be the king of development!",
    {
        left: 0.top: 200.fontFamily: "Comic Sans"./ / font
        fontSize: 50./ / size
        fontWeight: 800.// The font size can be a keyword (" normal ", "bold") or a number (100,200,400,600,800)
        shadow: "green 3px 3px 2px".// Text shadow, color, horizontal offset, vertical offset and blur size.
        underline: true./ / the underline
        linethrough: true./ / delete line
        overline: true./ / on line
        fontStyle: "italic".// Font style,normal or italic
        stroke: "#c3bfbf".// The color of stroke
        strokeWidth: 1.// The stroke width
        textAlign: "center".// Text alignment
        lineHeight: 1.5./ / line height
        textBackgroundColor: "#91A8D0".// The background color of the text}); canvas.add(text);Copy the code

2.9 event

Fabric uses the on method to initialize events and the OFF method to remove events.

Common events are as follows

  • “Mouse: Down” the mouse is pressed
  • Object: Add The object is added
  • “After :render” rendering is complete

And a whole bunch: Mouse events: “mouse: Down,” “mouse:move,” and “mouse:up…” Select related events: Before: Selection :cleared, Selection :created. For details, see the official document

canvas.on("mouse:down".function(options) {
    canvas.clear();
    let text = new fabric.Text("You ordered me.", {
        left: 200.top: 200}); canvas.add(text);console.log(options.e.clientX, options.e.clientY);
});
canvas.on("mouse:up".function(options) {
    this.text = "You didn't click 0.0 on me";
    canvas.clear();
    let text = new fabric.Text("You didn't click 0.0 on me", {
        left: 200.top: 200}); canvas.add(text);console.log(options.e.clientX, options.e.clientY);
});
Copy the code

Fabric allows you to attach listeners directly to objects in the Canvas canvas.

let rect = new fabric.Rect({ width: 100.height: 50.fill: "green" });
rect.on("selected".function() {
    console.log("Oh ho, you chose me.");
});

let circle = new fabric.Circle({ radius: 75.fill: "blue" });
circle.on("selected".function() {
    console.log("Hahaha, you chose me.");
});
Copy the code

3.0 Free painting

The Fabric Canvas isDrawingMode property is set to true to enable free drawing mode. Clicks and moves on the canvas are immediately interpreted as pencils or brushes.

let canvas = new fabric.Canvas("canvas");
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = "blue";
canvas.freeDrawingBrush.width = 5;
Copy the code

Three, the last

I am very happy to write this article. It is an article that I use to summarize the knowledge of Fabric with great care. I hope this article will be helpful to you. Canvas is often used in our daily development, but its API can be very tiring for dealing with complex business logic, so I’m sharing this article with you. I hope you found it helpful. If you get more than 500 likes, I will update the advanced part of Fabric.

I am very happy to be stronger with you! Follow me on my official account, Qianpozhai. I am Rong Ding, hopping over key caps and characters with me, shuttling through code and programs. 🤞