Drawing a rectangle
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.
How to do it...
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 ...
Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.