This is the 8th day of my participation in the August More Text Challenge

Plug-ins such as Echarts, G2, F2, antV, etc., can achieve some fancy reports, and sometimes we just need some plain and simple effects. Handwriting may take tens of k to complete. If the introduction of plug-ins can be several hundred (echarts in particular); A little knowledge of canvas can help us intercept useful things, or even build our own wheels.

Line drawing

HTML tags

<canvas id="can" width="500" height="500">Do not support the canvas</canvas>
Copy the code

The Canvas tag has only two attributes width and height. When the width and height are not set, the canvas initializes a width of 300 and a height of 150

Line drawing

The Canvas tag is rendering a canvas in the DOM, and all we need to do is drag it across the canvas. Here’s how to use it (ignore 3D)

const canvas = document.querySelector("#can");
const ctx = canvas.getContext("2d");/ / 3 d for webgl
ctx.beginPath()
ctx.moveTo(100.100);// Move to a point;
ctx.lineTo(200.100);// Midpoint coordinates;
ctx.lineWidth = '10';// Line width
ctx.strokeStyle = 'blue';/ / rgba (0222255, 5)

ctx.stroke();/ / stroke
Copy the code

1. First we get the canvas tag in the DOM. 2. Get the canvas context CTX by getContext; The moveTo method determines the starting coordinates of the brush (0,0 in the top left corner of the canvas). The lineTo method determines the coordinates where the brush will stop. The stroke method colors the lines we draw (again, unlike real paper and pencil, it has no color). We can use lineWidth to set the width of the line. Use srtrokeStyle to set the color of the line, which defaults to black.

The key way to

The above example shows the basic usage of line drawing. The key methods are as follows: 1.ctx.beginPath(); Start a new drawing; Used when drawing multiple lines. 2. Ctx.moveto (x,y); Move the brush to the specified coordinate as the starting coordinate of the brush. 3. Ctx.lineto (x,y); Stroke; Colour the drawn line

Don’t underestimate this simple line drawing, it’s enough to complete the canvas manual signature; The general idea is as follows: Start a new drawing while holding down the mouse and move the brush to the specified position. Track mouse coordinates as you move and loop through the lineTo and stroke methods. The effect is as follows: