HTML5 Canvas Reference - scale()








The scale() method scales the drawing to make the shape bigger or smaller.

The context.scale() function takes in two parameters: the first is the scale attribute for the x-axis, and the second is the scale attribute for the y-axis.

The value 1 is the normal scale for an object.

To double an object's size, we can set both values to 2.

Browser compatibility

scale() Yes Yes Yes Yes Yes




JavaScript syntax

context.scale(scalewidth,scaleheight>);

Parameter Values

Parameter Description
scalewidth Scales the width of the current drawing
scaleheight Scales the height of the current drawing

context.scale(1,1>) store the scaling. context.scale(2,2>) makes shapes twice as big as it should be in both x and y direction.

Example

context.scale(2,2>) makes shapes twice as big as it should be in both x and y direction.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--   w w  w  . j a  v a 2 s . c  om-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    ctx.strokeRect(5, 5, 50, 15);
    ctx.scale(2, 2);
    ctx.strokeRect(5, 5, 50, 15);
</script> 

</body>
</html>

The code above is rendered as follows:





Example 2

The following code resizes the text three times bigger.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--  w  ww  .  jav  a2s.  co m-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    ctx.scale(3, 3);
    ctx.fillText("java2s.com", 10, 10)
</script> 

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows that the scaling is accumulated.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from  w w  w .  j  a v a2  s  .c om-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    ctx.strokeRect(5, 5, 25, 5);
    ctx.scale(2, 2);
    ctx.strokeRect(5, 5, 25, 5);
    ctx.scale(2, 2);
    ctx.strokeRect(5, 5, 25, 5);
    ctx.scale(2, 2);
    ctx.strokeRect(5, 5, 25, 5);
</script> 

</body>
</html>

The code above is rendered as follows: