Copyright © tutorialspoint.com

HTML5 Canvas - Drawing Rectangles

previous next


Advertisements

There are three methods that draw rectangles on the canvas:

SNMethod and Description
1fillRect(x,y,width,height)
This method draws a filled rectangle.
2strokeRect(x,y,width,height)
This method draws a rectangular outline.
3clearRect(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:

Canvas Rectangle

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


previous next

Copyright © tutorialspoint.com