All graphics need to be drawn by path, while HTML5 canvas supports a kind of native graphics drawing - rectangle, and only supports this kind.

How to draw a rectangle:

//Create rectangle
//x: X coordinate of the upper left corner of the rectangle
//y: Y coordinate of the upper left corner of the rectangle
//width: the width of the rectangle in pixels
//height: the height of the rectangle in pixels
context.rect(x, y, width, height)

//Draw a filled rectangle
//x: X coordinate of the upper left corner of the rectangle
//y: Y coordinate of the upper left corner of the rectangle
//width: the width of the rectangle in pixels
//height: the height of the rectangle in pixels
context.fillRect(x, y, width, height)

//Draw a rectangular border
//x: X coordinate of the upper left corner of the rectangle
//y: Y coordinate of the upper left corner of the rectangle
//width: the width of the rectangle in pixels
//height: the height of the rectangle in pixels
context.strokeRect(x, y, width, height)

//Clears the specified rectangular area, which then becomes completely transparent.
//x: X coordinate of the upper left corner of the rectangle
//y: Y coordinate of the upper left corner of the rectangle
//width: the width of the rectangle in pixels
//height: the height of the rectangle in pixels
context.clearRect(x, y, width, height);

When using rect (x, y, width, height) to create a rectangle, you need to use the stroke () or fill () method to actually draw the rectangle on the canvas.

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.rect(20,20,160,50);
ctx.stroke();
ctx.beginPath();
ctx.rect(20,90,160,50);
ctx.fill();

It can be simplified as follows:

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.strokeRect(20,20,160,50);
ctx.fillRect(20,90,160,50);

Clear the specified area:

ctx.clearRect(90, 90, 50, 25);

All Comments

Leave a Reply Cancel Reply

Tips: Your email address will not be disclosed!

If you can't see clearly,please click to change...

Popular Posts

Collections