Summary -

In this topic, we described about the Canvas Scaling with detailed example.

Canvas scale used to scale the current drawing and draw enlarged shapes or scaled down shapes and bitmaps.

HTML5 canvas offers scale(x, y) method to decrease or increase the units in a canvas grid.This process brings two parameters(x, y) where x is the scale factor in the horizontal way and y is the scale factor in the vertical way.These two parameters should be positive numbers.

Values lesser than 1.0 reduce the unit size and values bigger than 1.0 expand the unit size.Establishing the scaling factor to exactly 1.0 doesn't affect the unit size( i.e. 1=100%, 0.5=50%, 2=200%, etc.).

Syntax -

context.scale(scalewidth,scaleheight);

Parameter Description
scalewidth Scales the width of the existing drawing (1=100%, 0.5=50%, 2=200%, etc.)
scaleheight Scales the height of the existing drawing (1=100%, 0.5=50%, 2=200%, etc.)

Example-

The following example to draw a square, scale to 500%, draw a square again, scale to 500%,draw square again.

-

<!DOCTYPE html>
<html>
  <body>
     <canvas id="myCanvas"  width="450" height="350" 
                   style="border:2px solid #00d3d3;">
     </canvas>
     <script>
         var c = document.getElementById("myCanvas");
         var ctx = c.getContext("2d");
         ctx.strokeStyle="#3257a8";
         ctx.strokeRect(3, 3, 9, 9);
         ctx.scale(5, 5);
         ctx.strokeRect(3, 3, 9, 9);
         ctx.scale(5, 5);
         ctx.strokeRect(3, 3, 9, 9);
     </script>
  </body>
</html>

Output -

Browser Support

The following browsers with versions in the table indicates the initial browser version that completely endorses the property.

Property Chrome Edge Firefox Safari Opera
scale( ) Yes 9.0 and above Yes Yes Yes