HTML5 Canvas - Drawing Rectangles



There are three methods that draw rectangles on the canvas −

Sr.No. Method and Description
1

fillRect(x,y,width,height)

This method draws a filled rectangle.

2

strokeRect(x,y,width,height)

This method draws a rectangular outline.

3

clearRect(x,y,width,height)

This method clears the specified area and makes it fully transparent

Here x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle and width and height are width and height of the rectangle.

Example

Following is a simple example which makes use of above mentioned methods to draw a nice rectangle.

<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         function drawShape() {
            
            // Get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');

            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
               
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');

               // Draw shapes
               ctx.fillRect(25,25,100,100);
               ctx.clearRect(45,45,60,60);
               ctx.strokeRect(50,50,50,50);
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
	
</html>

The above code would draw the following rectangle −

html5_canvas.htm
Advertisements