HTML Canvas - scale() Method



The HTML Canvas scale() method of the Canvas 2D API adds a scaling transformation to the canvas horizontally/vertically.

By applying the scaling factor, the scale of the Canvas element pixels is changed which results in the change of context size.

Syntax

Following is the syntax of HTML Canvas scale() method −

CanvasRenderingContext2D.scale(x, y);

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

x

Horizontal scaling value.

2

y

Vertical scaling value.

Return value

It applies scaling transformation to the context object inside the Canvas element.

Example

The following example draws a scaled rectangle onto the Canvas element using the HTML Canvas scale() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="400" height="300" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.scale(5, 5);
      context.fillStyle = 'blue';
      context.fillRect(5, 5, 70, 50);
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Scale Method

Example

The following methods scales a circle inside the Canvas element using the method scale().

<!DOCTYPE html>
<html lang="en">
<head>    
   <title>Reference API</title>
   <style>
     body {
       margin: 10px;
       padding: 10px;
     }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="450" style="border: 1px solid black;"></canvas>
   <script>
      var canvas=document.getElementById('canvas');
      var context=canvas.getContext('2d');
      context.scale(2,4);
      context.fillStyle = 'blue';
      context.arc(60,60,50,0,2*Math.PI);
      context.fill();
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Scale Method
html_canvas_shadows_and_transformations.htm
Advertisements