HTML5 canvas framework fabricjs learning notes - pictures and background

preface

This blog post is the second in the HTML5 canvas framework fabricjs learning notes series - pictures and backgrounds. It mainly introduces how to add picture objects, picture backgrounds and solid color backgrounds to the canvas.

For the introduction, introduction and index of the framework, see Learning notes on HTML5 canvas framework fabricjs (I) -- Introduction

Picture (fabric.Image)

The picture uses fabric Image class. The basic constructor is as follows:

    /**
     * Constructor
     * Image can be initialized with any canvas drawable or a string.
     * The string should be a url and will be loaded as an image.
     * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} element Image element
     * @param {Object} [options] Options object
     */
    initialize: function(element, options) {...}

Two parameters need to be passed in:

  1. Element: the type that can be passed in is htmlimageelement | htmlcanvas element | htmlvideoelement | String. When String is passed in, it must be the URL of the picture.
  2. option: some initial attributes, such as top, left, stroke, etc

However, in general, this loading method will not be used for the following reasons:

  1. The synchronized picture loading method will cause the problem of jamming when loading the canvas, which is more obvious when the picture is large.
  2. In addition to drawing fixed pictures in the canvas, most of the pictures are stored in the server and need to be downloaded and displayed in the canvas.

Load pictures asynchronously
To sum up, asynchronous loading is a better and more elegant approach. Here we use fabric Image. The source code of the fromurl method is as follows:

  /**
   * Creates an instance of fabric.Image from an URL string
   * @static
   * @param {String} url URL to create an image from
   * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument). Second argument is a boolean indicating if an error occurred or not.
   * @param {Object} [imgOptions] Options object
   */
  fabric.Image.fromURL = function(url, callback, imgOptions) {
    fabric.util.loadImage(url, function(img, isError) {
      callback && callback(new fabric.Image(img, imgOptions), isError);
    }, null, imgOptions && imgOptions.crossOrigin);
  };

Three parameters need to be passed in:

  1. URL: the URL of the picture resource.
  2. Callback: the callback method of asynchronous method, which will be called when the loading of picture resources is completed. As you can see from the second line of the source code, our callback method needs to accept two parameters:
    a. A created fabric Image object
    b. isError: whether an error occurred while loading the picture.
  3. imgOptions: similar to option in the previous article.

code

    // URL of the picture
    const imageURL = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fmmbiz.qpic.cn%2Fmmemoticon%2FQ3auHgzwzM59iamsj3CiaialyZwjTrz0DJQyuXjzv4o6oNJPNd5cOiblmlj2C36CLHOb%2F0.jpg&refer=http%3A%2F%2Fmmbiz.qpic.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1641360779&t=1f00cfde55ad1e6558db394d54cec43a";
    // Callback method
    let callback = (image, isError) => {
      if (!isError) {
        canvas.add(image);
      }
    };
    // attribute
    const properties = {
      left: 45,
      top: 45
    };
    fabric.Image.fromURL(imageURL, callback, properties);

Code description

  1. The URL of an image can be a download URL or a dataurl (such as data:image/gif;base64,...). Here is the URL of a yellow face expression found casually, which is invaded and deleted.
  2. The callback method, that is, the code that will be called when the picture loading succeeds or fails, can be used for the processing logic of success and failure respectively. For example, the logic we do here is to add the picture object to the canvas when it is successful.

result

background

In this framework, we can set solid color background and picture background.

Solid background

Solid color background is relatively simple. You only need to pass in a color value. The optional formats are

  1. 'rgb(255, 0, 0)': RGB decimal color
  2. 'rgba(0, 255, 0, 0.6)': rgb color with transparency, i.e. rgba
  3. #11D2F0: hexadecimal color
  4. lightblue: color word

code

  const color = "lightblue";
  canvas.setBackgroundColor(color);
  // The canvas must be re rendered to show the new background
  canvas.renderAll();

Code description

After changing the canvas background, you need to call canvas Renderall() re renders the canvas so that you can see the new background of the canvas. This method will be often used in the future.

result

Picture background

The loading method of the picture background is similar to the picture object in the previous article

code

    // URL of the picture
    const imageURL = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0137835b98a43da80121a0f75cd75c.jpg%403000w_1l_0o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1643713176&t=7639992e8e27ae6a0d15d664b8e02142";
    // Callback method
    const callback = (image, isError) => {
      // Sets the horizontal scaling of the picture background
      image.scaleX = canvas.width / image.width;
      // Sets the vertical scaling of the picture background
      image.scaleY = canvas.height / image.height;
      canvas.setBackgroundImage(image);
      canvas.renderAll();
    };
    fabric.Image.fromURL(imageURL, callback);

Code description

  1. Still use fabric Image. The fromurl loads the image asynchronously, but the logic in the callback method has changed.
  2. scaleX and scaleY are the scaling of the picture background in the horizontal and vertical directions, respectively. Set here to zoom the picture to fully fill the canvas. If it is not set, because the picture is much larger than the canvas, only part of the upper left corner of the picture is displayed in the canvas.

result

Postscript

This section describes how to add a picture object to the canvas and set a solid color background and picture background for the canvas.

Pictures are different from other objects. The amount of data is large and may be several megabytes at any time. Therefore, the serialization and storage of canvases need special processing. See the subsequent chapters for details.

Keywords: Javascript Front-end html5

Added by agmorgan on Mon, 03 Jan 2022 20:11:55 +0200