This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging


What is canvas?

The HTML5 < Canvas > element is used for drawing graphics, which is done through JavaScript. The < Canvas > tag is just the graphics container, you must use the script to draw the graphics.


Canvas compatibility


How to use Canvas?

The document.getelementByID () method gets a reference to the HTML < Canvas > element. Then the HTMLCanvasElement. GetContext () method to get the elements of the context, the image will be rendered in the later.

The CanvasRenderingContext2D interface performs the actual drawing. The fillStyle property turns the rectangle green. The fillRect() method places its top left corner at (10, 10) and sets its size to 300 wide and 200 high. .

As shown in figure:


Canvas coordinates

Canvas is a two-dimensional grid.

The top left corner of the canvas is (0,0)

The fillRect method above takes arguments (0,0,150,75).

Draw a rectangle of 150×75 on the canvas, starting at the top left corner (0,0).

Canvas – path

To draw a line on the Canvas, we will use the following two methods:

  • moveTo(x,yDefine the line starting coordinates
  • lineTo(x,yDefine the line end coordinates

To draw a line we must use an “ink” method, like stroke().

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(100.0);
ctx.lineTo(300.500); ctx.stroke();

Copy the code

The effect is as follows:

Canvas to write text

Using canvas to draw text, the important properties and methods are as follows:

  • Font – Defines the font
  • fillText(text,x,y) – Draws solid text on the canvas
  • strokeText(text,x,y) – Draws hollow text on the canvas

Use the fillText () :

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="50px Arial";
ctx.fillText("Hi,LiMing".14.90);

Copy the code

Problems with Canvas

1. How to set different styles

Add ctx.beginPath() before writing the style;

Note: Canvas definition

 var c=document.getElementById("myCanvas");
 var ctx=c.getContext("2d");
Copy the code

2. When converting canvas to image format, the internally loaded images are not displayed

Use the img complete attribute to determine whether the image has been loaded

var interval = setInterval(function () {
              if(img.complete == true) {clearInterval(interval );
                 var base64 = canvas.toDataURL("image/png"); }},500);   
Copy the code

Note: The timer is used to detect every 0.5 seconds, and the timer is cancelled after the image is loaded, and the canvas is converted to the image format, so as to avoid the internal image loss of the Canvas when the image is transferred