In this recipe, we'll learn how to draw the only built-in shape provided by the HTML5 canvas API, a rectangle. As unexciting as a rectangle might seem, many applications use them in one way or another, so you might as well get acquainted.
Follow these steps to draw a simple rectangle centered on the canvas:
Define a 2D canvas context:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");
Draw a rectangle using the
rect()
method, set the color fill with thefillStyle
property, and then fill the shape with thefill()
method:context.rect(canvas.width / 2 - 100, canvas.height / 2 - 50, 200, 100); context.fillStyle = "#8ED6FF"; context.fill(); context.lineWidth = 5; context.strokeStyle = "black"; context.stroke(); };
Embed the canvas tag inside the body of the HTML document:
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas...