HTML part:
<canvas the above mentioned id = " canvas " width = " 400 " height = " 400 " > Your browser does not support the canvas too low a hurry for a bar </ canvas>
JS part:
① acquisition canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
③ start a new path (on the canvas again from the head)
ctx.beginPath ();
ctx.moveTo(0, 0);
⑤ line width setting
ctx.lineWidth = 2;
⑥ color children brush strokes set
ctx.strokeStyle = "red";
⑦ start drawing a line, crossed the lineTo (abscissa, ordinate) to draw a square
ctx.lineTo(400, 0); ctx.lineTo(400, 400); ctx.lineTo(0, 400); ctx.lineTo(0, 0);
⑧ execution draw
ctx.stroke();
Results are as follows:
⑨ closed current path (if not closed, the previous code after the code coverage, such as color pen, the pen width, etc.);
ctx.closePath();
⑩ save the current drawing
ctx.save();
End end
We are in the inside and then draw a square
ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineWidth = 2; ctx.strokeStyle = "green"; ctx.lineTo(100, 300); ctx.lineTo(300, 300); ctx.lineTo(300, 100); ctx.lineTo(100, 100); ctx.stroke();
If you draw a closed figure we may be filled
Set fill color:
ctx.fillStyle = "yellow";
filling:
ctx.fill();
Results are as follows:
last step:
Clear canvas, we can clear the entire canvas can also remove part of the canvas
Clear canvas part:
Clear the portion of the canvas clearRect (x, y, x until the end, the end thereof Y );
x: X coordinate of the upper left corner to clear the portion
y: Y coordinate of the upper left corner to clear the portion
ctx.clearRect(0, 0, 400, 200);
Results are as follows: I am here to clear the upper half of the canvas
You can also clear the entire canvas clearRect (0, 0, width of the canvas, the canvas high);
ctx.clearRect(0, 0, 400, 400);
Here is the entire canvas cleared
Happy end!