Recently, canvas is needed in some projects. As an old ape who has not used canvas for a long time, everything is a brand new start. If it’s the beginning, then it’s the simplest way to do it, what the hell is there to do with this damn fascinating front end.

The basic method of canvas

Canvas only supports two forms of graph drawing: rectangle and path (a line segment connected by a series of points). All other types of graphics are made up of one or more paths. On the one hand, it may be inconvenient to use, but on the other hand, the simple API makes learning costs correspondingly lower.

React was used in the project. Here I use React Hook as an example.

To start, we need to get the canvas.

// initialize canvas ref; const canvasRef = useRef(); // Get render context function and draw function object; const [ctx, setCtx] = useState(); UseEffect (() => {// The project uses ts [?.] syntax as a non-null judgment syntax. If js is used, es2020 already supports this syntax. setCtx(canvasRef? .current? .getContext('2d')); } []); <canvas ref={canvasRef} height={1001} width={1001} ></canvas>Copy the code

The process of drawing lines:

// This method is equivalent to picking up a brush ctx.beginPath(); Ctx.moveto (startX, startY); ctx.moveto (startX, startY); Ctx.lineto (endX, endY); // Connect the start position to the end position so that a line is drawn ctx.stroke();Copy the code

The process of drawing and filling a rectangle:

// Pick up the brush ctx.beginPath(); Ctx. fillStyle = 'red'; Ctx. font = '12px Georgia'; Ctx.filltext (item.class, item.date * 50, item.room * 50 + 12); Ctx.beginpath (); Ctx. fillStyle = 'rgba(0, 0, 200, 0.1)'; Ctx.fillrect (item.date * 50, item.room * 50 + 1, item.length, 50);Copy the code

Above are simple lines and rectangles with text, which are easier to understand if combined with real objects.

There is a problem here, because if we choose integers as the starting point, that is, the above coordinate points, the line will be very thick:

But if every coordinate point ends in 0.5, then this situation disappears:If you compare the two pictures, you can feel the difference.

This is because canvas rendering is centered on the pixels of coordinates, extending half pixels to the left and right, and then the remaining pixels will blur rendering, resulting in visually wider and unclear lines. Therefore, 0.5 coordinates can be added to make it render from integer coordinates. If you are interested, refer to the MDN documentation.