HTML5 - How to draw a rectangle

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Created: Maveric (30 Jun 2011)
Last edited: hamishwillee (04 May 2012)

This article explains how to create a rectangle using the graphics capabilities of HTML5


Drawing a rectangle with HTML5 is easy. What you need, is to instantiate the graphics context and then use fillStyle() and fillRect() methods.

To the FillStyle we will offer a hexadecimal color code as parameter. This color will then be used to draw the rectangle.

For FillRect, which will actually do what we want to see on the screen, a rectangle that is, we will be giving two points in the x and y coordinate system. The first point (x,y) will be where the drawing starts and the second point (x,y) will define where the drawing will end.


HTML5 supported browser.

Example code

Change the values to see the difference. This code will create a 800x600 black box on screen.

<canvas id="myCanvas" width="800" height="600">
Your Browser does not support the HTML5 CANVAS Property. //displays on a non-HTML5 supporting browser.
<script type="text/javascript">
var myCanvas = document.getElementById("myCanvas");
var myContext = myCanvas.getContext("2d");
This page was last modified on 4 May 2012, at 04:04.
45 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.