HTML Canvas - transform() Method



The HTML Canvas transform() method of Canvas API multiplies the current transformation by using the method arguments provided.

Syntax

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

CanvasRenderingContext2D.transform(a, b, c, d, e, f); 

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

a

Horizantal scaling.

2

b

Vertical skewing

3

c

Horizantal skewing

4

d

Vertical scaling

5

e

Horizantal translation

6

f

Vertical translation

Return value

It applies transformation matrix to the current context object of CanvasRenderingContext2D interface inside the Canvas element.

Example 1

The following program applies transformation matrix to a square drawn onto the Canvas element using the HTML Canvas transform() method.

<!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="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setTransform(0.9, 0.8, 0.7, 0.6, 0.5, 0.4);
      context.fillRect(20, 20, 100, 100);
   </script>
</body>
</html>

Output

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

HTML Canvas Transform Method

Example 2

The following example applies transformation matrix to a circle using the method transform().

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="100" height="120" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setTransform(0.1, 0.2, 0.3, 0.4, 0.5, 0.6);
      context.arc(100, 100, 100, 0, 2 * Math.PI);
      context.fill();
   </script>
</body>
</html>

Output

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

HTML Canvas Transform Method
html_canvas_shadows_and_transformations.htm
Advertisements