Translating the canvas context

In this recipe, we'll learn how to perform the most basic and commonly used transformation available with the HTML5 canvas API—translation. If you're unfamiliar with transformation terminologies, "translation" is just a fancy way of saying "move". In this case, we'll be moving the context to a new location on the canvas.

Translating the canvas context

How to do it...

Follow these steps to draw a translated rectangle moved to the center of the canvas:

  1. Define the canvas context and the dimensions for the rectangle:
    window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var rectWidth = 150; ...

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.