Canvas- lines, rectangles and circles

Article Directory

straight line

const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

moveToIt is mobile, can be understood as moving the brush. lineToIt is the designated location to draw a straight line from its current position. Effect of the above code is as follows:

Here Insert Picture Description

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 strokemethod will be two lines are drawn again, the two are blue.

Here Insert Picture Description

The reason is because moveTo, lineTothese operations are memory operations and are not drawn to the screen, call the strokemethod when it truly is drawn, so the memory stored in the path of the two lines, so the second strokemethod 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 strokecall method after beginPathmethod can be. Stored in memory before this method will clear the path.
Here Insert Picture Description

rectangle

const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
ctx.strokeRect(100, 100, 150, 100);

[Image dump outer link failure (img-ljWWK3pD-1562075809430) (http://note.youdao.com/yws/res/15763/486CA587848349F0A4638764447B91E3)]

Although you can draw a rectangle by way of drawing a line, but call the strokeRectmethod 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();

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/hjc256/article/details/94485198