Draw Rectangles in HTML5 Canvas

SEARCH THIS SITE

Custom Search



JavaScript is now used to draw and fill rectangles in an HTML 5 canvas.

1 - Draw and fill rectangles using rect() and fillRect()


Copy and paste the code below in Notepad++ (or any other HTML5 editor) and run it.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvasShapes" width="400" height="400" style="border:4px solid #0000ff;">
This browser does not support the HTML5 canvas tag. </canvas>
<script>

var canvas = document.getElementById("canvasShapes");
var ctx = canvas.getContext("2d");

// draw a line
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.lineWidth = 1;
ctx.moveTo(100,100);
ctx.lineTo(0,0);
ctx.stroke();

// draw a Rectangle
ctx.beginPath();
ctx.strokeStyle = "green";
ctx.lineWidth = 2;
ctx.moveTo(100,100);
ctx.rect(100,100,100,150);
ctx.stroke();

// fill a rectange
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.lineWidth = 2;
ctx.fillRect(200,200,100,150);
ctx.fill();

</script>
</body>
</html>

rectangle.

Explanations
A line is first drawn to help understand the location of the different rectangles.
Each item to be drawn has its own path.
The statements ctx.rect(100,100,100,150); and ctx.fillRect(200,200,100,150); are used to draw a rectangle (green) and fill a rectangle (blue) respectively. Both methods are of the form ctx.rect(x,y,w,h) and ctx.fillRect(x,y,w,h) where:
x is the x-coordinate from the top left corner of the canvas(x positive to the right).
y is the y-coordinate from the top left corner of the canvas (y positive downward).
w is the width of the rectangle.
h is the height of the rectangle.

1 - Draw Rectangles using moveTo() and lineTo()

A rectangle may also be drawn by drawing the 4 sides of the rectangle. An example below shows how to draw rectangle whose sides have different colors.

Copy and paste the code below in Notepad++ (or any other HTML5 editor) and run it.


<!DOCTYPE html>
<html>
<body> <canvas id="canvasShapes" width="400" height="400" style="border:4px solid #0000ff;">
This browser does not support the HTML5 canvas tag. </canvas>
<script>
var canvas = document.getElementById("canvasShapes");
var ctx = canvas.getContext("2d");

// draw a line
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.lineWidth = 5;
ctx.moveTo(50,50);
ctx.lineTo(150,50);
ctx.stroke();

// draw a line
ctx.beginPath();
ctx.strokeStyle = "green";
ctx.lineWidth = 5;
ctx.moveTo(150,50);
ctx.lineTo(150,250);
ctx.stroke();

// draw a line
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.moveTo(150,250);
ctx.lineTo(50,250);
ctx.stroke();

// draw a line
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.moveTo(50,250);
ctx.lineTo(50,50);
ctx.stroke();

</script>
</body>
</html>

rectangle defined by points.

More Free HTML5 Canvas Tutorials