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>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Rectangle</title>
<script>
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");
canvasCtx.clearRect(0,0,200,200);
}
</script>
</head>
<body>
<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>
<div id="drawingsurface">
<canvas id="mycanvas" width="200" height="200"/>
</div>
</body>
</html>
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
- Getting Started with Canvas
- Rectangles
- Strokes and Fills
- Drawing Text
- Paths
- Circles and Arcs
- Images
- Graphs With Canvas
Back to HTML5 Series