Scale Transformation in Canvas: HTML5

Today lets learn about scale transformation.

Syntax
scale(x, y);
Scales drawing operations by multiples of x and y.

Related read: Translate Transformation in Canvas: HTML5 (important)

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Scale Transformation of 2 rectangles
myScript.js

 context.fillStyle  = "red";
 context.fillRect(10, 10, 50, 50);
 
 context.scale(2, 2);
 context.fillStyle  = "blue";
 context.fillRect(40, 40, 50, 50);

Here we have 2 rectangles with red and blue color, at two different x, y axis, but with same height and width i.e., 50px each
But using scale() method, we scale the second rectangle by 2. So the second rectangle is drawn at 80px x-axis, 80px y-axis with a width and height of 100px.

JavaScript file: Scale Transformation of 3 rectangels
myScript.js

 context.fillStyle  = "red";
 context.fillRect(10, 10, 50, 50);
 context.save();
  
 context.scale(2, 2);
 context.fillStyle  = "blue";
 context.fillRect(40, 40, 50, 50);
  
 context.restore();
 context.scale(0.5, 0.5);
 context.fillStyle  = "green";
 context.fillRect(100, 40, 50, 50);  

Here we save the scale value of first rectangle(which is 1,1), and restore it for the third rectangle – using canvas status. If we don’t use canvas status, then the (0.5, 0.5) scale for the third rectangle will be applied with respect to the second rectangle which has a scale of (2, 2). Hence, third rectangle scale will be (1.5, 1.5). As 2.0 – 0.5 = 1.5

JavaScript file: Full Free Code
myScript.js

window.onload = canvas;

function canvas()
{
    var myCanvas = document.getElementById("myCanvas");
 
    if( myCanvas && myCanvas.getContext("2d") ) 
    {
 var context         = myCanvas.getContext("2d");
 context.fillStyle  = "red";
 context.fillRect(10, 10, 50, 50);
 context.save();
  
 context.scale(2, 2);
 context.fillStyle  = "blue";
 context.fillRect(40, 40, 50, 50);
  
 context.restore();
 context.scale(0.5, 0.5);
 context.fillStyle  = "green";
 context.fillRect(100, 40, 50, 50);
    }
}  

With save and restore methods applied:
1st rectangle: (1.0, 1.0);
2nd rectangle: (2.0, 2.0);
3rd rectangle: (0.5, 0.5);

Without save and restore methods applied:
1st rectangle: (1.0, 1.0);
2nd rectangle: (2.0, 2.0);
3rd rectangle: (1.5, 1.5);

Scale Transformation in Canvas: HTML5



YouTube Link: https://www.youtube.com/watch?v=kGLYu62ao6Q [Watch the Video In Full Screen.]



The scale() transformation causes drawing operations to be multiplied by a given scale factor in the x and y direction.

scale() transformation can be applied to any drawing operation on the canvas, like circles, triangle, images etc.