HTML5 Recipes: Rectangles

In this recipe, we shall look at how to draw a rectangle using the HTML5 Canvas API. The code for the recipe is shown below:

<!DOCTYPE html>
<meta charset="utf-8">
<title>Canvas Rectangle</title>
function draw_rectangle() {

 var canvasObj = document.getElementById("mycanvas");
 var canvasCtx = canvasObj.getContext("2d");
 canvasCtx.strokeRect(0, 0,200,200);

function clear_canvas() {
	var canvasObj = document.getElementById("mycanvas");
	var canvasCtx = canvasObj.getContext("2d");
    <div id="instructions">
     <a href="#" onclick="draw_rectangle();return false">Click to draw</a>
     <a href="#" onclick="clear_canvas();return false">Click to clear</a>

 <div id="drawingsurface">
  <canvas id="mycanvas" width="200" height="200"/>

Let us go through the code in brief. We declare a canvas with a height and width of 200 pixels. The main method is draw_rectangle(). First, we get a handle to the 2D context and simply call the strokeRect() method. The strokeRect() method takes 4 parameters (x,y,w,h) where x,y are the top-left co-ordinates and w,h are the width and height of the rectangle respectively.

See it in action here.

The strokeRect() method simply draws the rectangle and uses the default stroke color for the edges of the Rectangle. There is an alternative method named fillRect() that you can use to draw a rectangle and it will be filled with the default fill Style. The fillRect() method also takes the same parameters as the strokeRect() method i.e. (x,y,w,h) except that it also fills the Rectangle area with the current canvas context fill Color. Note that by default, the fill color is black.The only change to the above code is replacing the strokeRect() method with the fillRect() method.

canvasCtx.fillRect(0, 0,200,200);

See it in action here.

HTML5 Canvas Recipes

  1. Getting Started with Canvas
  2. Rectangles
  3. Strokes and Fills
  4. Drawing Text
  5. Paths
  6. Circles and Arcs
  7. Images
  8. Graphs With Canvas

Back to HTML5 Series


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s