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);
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.