HTML Canvas - setTransform() Method



The HTML Canvas setTransform() method of Canvas 2D API resets the current transformation matrix if applied to the identity matrix and then invokes a new transformation as given by the arguments of this method.

Syntax

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

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

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1 matrix

This is a newer type of parameter which can be passed to the object. It represents a 2D transformation to set. The matrix is assigned as follows −

$\begin{Bmatrix} a& c& e \\ b& d& f\\ 0& 0& 1\\ \end{Bmatrix}$

2

a

Horizontal scaling.

3

b

Vertical skewing

4

c

Horizantal skewing

5

d

Vertical scaling

6

e

Horizantal translation

7

f

Vertical translation

Return Value

A new transform applied to the context object of CanvasRenderingContext2D interface is drawn on the Canvas element.

Example 1

The following example applies the HTML Canvas setTransform() method to a rectangle and draws it onto the Canvas element.

<!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.fillStyle='purple';
      context.setTransform(1, 0.5, 0.7, 0.9, 0.8, 0);
      context.fillRect(15, 15, 100, 60);
   </script>
</body>
</html>

Output

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

HTML Canvas SetTransform Method

Example 2

The following example applies transformation matrix to circle drawn inside the Canvas element using the method setTransform().

<!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.fillStyle = 'purple';
      context.setTransform(1, 0.5, 0.7, 0.9, 0.8, 0);
      context.arc(100, 50, 75, 0, 2 * Math.PI);
      context.fill();
   </script>
</body>
</html>

Output

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

HTML Canvas SetTransform Method
html_canvas_shadows_and_transformations.htm
Advertisements