canvas beginner, to teach you how to draw lines on the canvas canvas

html5 canvas in order to achieve a very cool effect you can use 2d graphics, all incoming canvas (canvas) used for game development, and low version ie not supported
    note:
    1.canvas default size is with: 300 height: 150
    2. If your browser does not support the canvas, the browser will display the contents of the canvas tag, but does not run canvas drawn effect
    3.canvas is the line element 
    When 4.canvas embodiment provided only by the width and height of the label to the property, can not be provided by the style css height and width, can not be provided by js, i.e. canvas.style.height / width, through the label that the set the image width and height will stretch drawing canvas
    The size may be provided directly to the canvas properties

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');
② create a brush on the canvas in the canvas
var ctx = canvas.getContext("2d");

③ start a new path (on the canvas again from the head)

ctx.beginPath ();
④ starting position
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!

Line width setting

Guess you like

Origin www.cnblogs.com/wulicute-TS/p/11881609.html
Recommended