Calculator Collection | About the Calculator Series | Inside the Code | Home

Draw Rectangle on Canvas

Enter the size and position parameters for your rectangle. The JavaScript code draws it on the canvas.

Width (pixels)
Height (pixels)
X Start (pixels)
Y Start (pixels)

Download / Basics

To run or modify on your PC, download a simple version of this file with image (*.zip).
For a quick tour of some JavaScript / HTML basics, check out Inside the Code.


While searching for Javascript examples, I ran across a tutorial showing how to draw basic graphics on the canvas - cool! It looked possible without a huge overhood of code (or steep learning curve).

First, you need to get a reference to the HTML canvas ID in the HTML body.

 var canvas = document.getElementById("canvas");

Next, get a reference to the "2D" drawing element.


It's that simple, now you can start drawing! Create a rectangle using:


which sets up a fill style of a light gray color "#dddddd", then draws a filled rectangle starting at x=0, y=0 and spans x=501 pixels wide and y=201 pixels tall. This serves as our canvas background.

IMPORTANT! The canvas coordinates x=0, y-0 are located in the upper left-hand corner of the canvas rectange! As x increases, the position moves to the right. As y increases, the possition moves down. 

Now. let's get the entered parameters describing the line rectangle to be drawn. The "Number" function takes the text input from the form and converts it to a number.

 // get values directly from form
 var H=document.myForm.H.value
 var W=document.myForm.W.value
 var xs=document.myForm.xs.value
 var ys=document.myForm.ys.value

Instead of using the rectangle function, this code demonstrates drawing by using individual line strokes. The code below begins a line path. After moving to the start coordinates (xs,ys), it creates lines to the 4 corners of a rectangle that's W pixels wide by H pixels high.

// define line
 ctx.lineWidth = 1;
 ctx.strokeStyle = "rgb(11,11,11)";
 // draw rectangle
 ctx.moveTo( xs  , ys   );
 ctx.lineTo( xs  , ys+H );
 ctx.lineTo( xs+W, ys+H );
 ctx.lineTo( xs+W, ys   );
 ctx.lineTo( xs  , ys   );


The heart of the HTML is the canvas tag.

<canvas id="canvas" width="501" height="201"></canvas>

which defines it's reference ID for use in the JavaScript code and its dimensions.