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.

Drawing a rectangle

How to do it...

Follow these steps to draw a simple rectangle centered on the canvas:

  1. Define a 2D canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Draw a rectangle using the rect() method, set the color fill with the fillStyle property, and then fill the shape with the fill() 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.