Press "Enter" to skip to content

Drawing a rectangle in canvas | Drawing Shapes with Canvas

This article shows how to draw a rectangle shape using the canvas tag in HTML5. cavas tag in HTML5 extends the possibilities of drawing various shapes like, rectangles, circles,etc. with various filling styles, like solid fills, gradient fills, pattern fills, etc.

HTML code:

<body>
<div>
<canvas id="myCanvasElm" width="250" height="250">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>
<button onclick="drawRectagle();">drawRectagle</button>
</body>

JavaScript code:

function drawRectagle(){
// Get the Canvas element
var myCanvas = document.getElementById("myCanvasElm");
if (myCanvas.getContext) {
// If Canvas is supported
var canvasContext = myCanvas.getContext('2d');
// Set the fill style to #00FF00
canvasContext.fillStyle = "#00FF00";
// Draw the rectangle 100x50 pixels in dimension at x/y 10,10
canvasContext.fillRect(10, 10, 100, 50);
}
}

NOTES:

getContext(): This method returns an object that provides methods and properties for drawing on the canvas.
fillRect(): This method draws a “filled” rectangle.context.fillRect(x,y,width,height).
fillStyle: The fillStyle property sets or returns the color, gradient, or pattern used to fill the drawing. context.fillStyle=color|gradient|pattern;