Scaling the canvas context

In addition to translations and rotations, the HTML5 canvas API also provides us with a means for scaling the canvas context. In this recipe, we'll scale down the height of the canvas context using the scale() method.

Scaling the canvas context

How to do it...

Follow these steps to draw a scaled rectangle:

  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;
        var rectHeight = 75;
  2. Translate the canvas context and then scale the canvas context height by 50%:
     // translate context to center of canvas context.translate(canvas.width ...

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.