Web | This Site

HTML-5 Tutorial
HTML5 Tag Reference
HTML5 Useful References
HTML5 Tools
HTML5 Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# HTML5 Canvas - Drawing Rectangles

There are three methods that draw rectangles on the canvas:

SN | 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>
    <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 onload="drawShape();">
       <canvas id="mycanvas"></canvas>
    </body>
    </html>

This would draw following rectangle:

To learn above concept - Do Online Practice using latest version of either Safari or Opera.

Advertisement

Online Image Processing

Indian Baby Names