[Js master path] html5 canvas tutorial, html5canvas
To draw 1 px lines in the canvas, it is not acceptable by default.
1 context.beginPath(); 2 context.moveTo( 100, 100 ); 3 context.lineTo( 400, 100 ); 4 context.closePath(); 5 context.stroke(); 6 7 context.beginPath(); 8 context.strokeStyle = 'red'; 9 context.moveTo( 100.5, 200.5 );10 context.lineTo( 400.5, 200.5 );11 context.closePath();12 context.stroke();
In the above Code, context is the canvas context. In this code, I drew two lines. The line above is not 1px, and the line below is 1px.
You may not see clearly whether the black line is 1px. You can put them in the drawing software or photoshop, zoom in, and open the coordinates to see the following results:
Obviously, this black line occupies 2 rows, that is, 2 PX, and the red line occupies one row, that is, the true 1px line segment, that is, in the canvas, if you need to draw a line segment of 1px, add 0.5 to the coordinates. Next, we will draw a coordinate system with a scale of 10px in the x and y directions.
1 drawGrid('#09f', 10, 10); 2 function drawGrid(color, stepx, stepy) { 3 context.save() 4 5 context.strokeStyle = color; 6 context.lineWidth = 0.5; 7 context.clearRect(0, 0, context.canvas.width, context.canvas.height); 8 9 for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {10 context.beginPath();11 context.moveTo(i, 0);12 context.lineTo(i, context.canvas.height);13 context.stroke();14 }15 16 for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {17 context.beginPath();18 context.moveTo(0, i);19 context.lineTo(context.canvas.width, i);20 context.stroke();21 }22 23 context.restore();24 }