HTML5 Canvas - Rectangle
You can always draw a rectangle using 4 lines on the canvas. But HTML 5 provides a better way of drawing a rectangle - using the rect method. The rect method looks as follows
context.rect(x, y, width, height);
Where,
x,y => Coordinates of the top left corner of the rectangle
width = > width of the rectangle
height => height of the rectangle
The following code will draw a rectangle and will also fill it in yellow color.
<!DOCTYPE html5> <html> <body> <canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;"> </canvas> <script> var c1=document.getElementById("canvas1"); var context1=c1.getContext("2d"); context1.beginPath(); context1.rect(60,60,100,50); context1.lineWidth=5; context1.strokeStyle="blue"; // Now fill the rectangle with yellow color context1.fillStyle = 'yellow'; context1.fill(); context1.stroke(); </script> </body> </html> |
Try this example Online
Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in coordinates, height and width and the fill color, to see how it looks like.
Congratulations !!! You have been able to draw a rectangle in HTML5.