HTML5 canvas fillRect

05.Aug.2010

The canvas element is used to draw graphics on a web page. It can be used for 2D or 3D drawing. In this example, we shall be drawing a square in center of canvas element. So, in order to draw a rectangle you need to use fillRect function with parameters as shown:

canvas.fillRect( X, Y, WIDTH, HEIGHT);

Canvas is a rectangular area on your web page, and using JavaScript, we can control every single pixel on it. The canvas element has several methods for drawing paths, rectangles, filled rectangles (even with gradient), circles, images, and much more. This snippet shows how to draw square as width and height of rectangle on our HTML5 canvas are 100px each.

1
2
3
4
5
6
7
8
9
10
11
<canvas id="html5-canvas" width="200" height="200"></canvas>
 
<script>
/* Use JS to fetch canvas element */
var canvas = document.getElementById('html5-canvas');
/* Get 2D context of canvas */
var c = canvas.getContext('2d');
c.fillStyle = '#3ac6e5';
/* Draw a rectangle on canvas */
c.fillRect(50, 50, 100, 100);
</script>

Preview of HTML5 canvas fillRect

In this preview you can see how previous script forms rectangle on canvas.