Article Directory
straight line
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
moveTo
It is mobile, can be understood as moving the brush. lineTo
It is the designated location to draw a straight line from its current position. Effect of the above code is as follows:
It looks nothing issue, butIn fact, the first line is then drawn twice。
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.moveTo(100, 0);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'blue';
cts.stroke();
If two lines are drawn, respectively, it should be a red, a blue, if the latter stroke
method will be two lines are drawn again, the two are blue.
The reason is because moveTo
, lineTo
these operations are memory operations and are not drawn to the screen, call the stroke
method when it truly is drawn, so the memory stored in the path of the two lines, so the second stroke
method is called when , the first line was also drawn.
Then how to solve this problem?
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.strokeStyle = 'red';
cts.stroke();
ctx.beginPath(); //引入beginPath方法
ctx.moveTo(100, 0);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'blue';
cts.stroke();
Only the first stroke
call method after beginPath
method can be. Stored in memory before this method will clear the path.
rectangle
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.strokeRect(100, 100, 150, 100);
Although you can draw a rectangle by way of drawing a line, but call the strokeRect
method will be more convenient.
The method takes four parameters, the first two are drawn to the upper left corner of the rectangular coordinates, the latter two are the width and height of the rectangle.
circle
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.arc(300, 300, 100, 0, 2*Math.PI);
ctx.stroke();