Draw Rectangle on Canvas
Download / Basics
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 H=Number(H); W=Number(W); xs=Number(xs); ys=Number(ys);
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.beginPath(); 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 ); ctx.stroke();
The heart of the HTML is the canvas tag.
<canvas id="canvas" width="501" height="201"></canvas>