Use canvas to sign a picture

Time:2021-4-29

Demand:

  • Sign the author’s name in the picture and center it in the specified underline position.

  • The image generated by canvas can be downloaded and the size is suitable for printing

Realization idea:

Using canvas to realize a canvas

    this.canvas = document.createElement('canvas');
    this.canvas.className = 'cert-canvas';
    this.ctx = this.canvas.getContext('2d');

Then draw the picture on canvas

let img = new Image();
    img.src = img_path;
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = () => {
      this.canvas.width = img.width; // The size of the canvas is set to the size of the picture
      this.canvas.height = img.height;
      this.ctx.drawImage(img, 0, 0, img.width, img.height);
    };

Add text to canvas

  draw_time_text(text, x, y) {
    this.ctx.font = '18px Helvetica';
    this.ctx.textAlign = 'center';
    this.ctx.fillText(text, x, y);
  }

Problems and solutions:

Center horizontal text on the canvas

To solve the problem, find the midpoint of the underline in the specified position, and then use thethis.ctx.textAlign = 'center';To center the text around the midpoint

Color text

This.ctx.fillstyle ='color value ';

Security issues of non homologous images

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Because of the security of the browser, if the image resources of foreign domain are used in the process of drawing with canvas, the security exception will be thrown when todataurl(). In order to solve this problem, we do not set the credential flag for the CORS request of the image when we introduce the image. Namely img.setAttribute('crossOrigin', 'anonymous');

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]