HTML5 Canvas Reference - setTransform()








By using the transformation matrix the setTransform() method can scale, rotate, move, and skew the current context.

We can use the setTransform() method to reset the current transform.

Browser compatibility

setTransform() Yes Yes Yes Yes Yes

JavaScript syntax

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

Parameter Values

Parameter Description
a Scales the drawings horizontally
b Skews the drawings horizontally
c Skews the drawings vertically
d Scales the drawings vertically
e Moves the the drawings horizontally
f Moves the the drawings vertically




Example

The following code shows how to use setTransform() method.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<!--from  ww  w.  j  a  v a  2 s .  co m-->
<script>

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 250, 100)
    
    ctx.setTransform(1,0.5, -0.5, 1, 50, 10);
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 250, 100);
    
    ctx.setTransform(1,0.5, -0.5, 1, 50, 10);
    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, 250, 100);

</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code uses setTransform() to create animation.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='200px' height='200px'/>
<script type='text/javascript'>
var context2D = document.getElementById("canvas").getContext("2d");
var x=1;
function drawAnimation(){<!--   w  w  w.  j a va2  s .  c  o  m-->
    context2D.clearRect(0, 0, canvas.width, canvas.height);
    context2D.save();
    context2D.setTransform(1, 1, x*.8, 1, x*.8, x*.8);
    context2D.fillRect(x+10,x-10,x+40,x+40);
    context2D.restore();
    x+=0.1;
    setTimeout(function(){drawAnimation()},200);
}
drawAnimation();

</script>
</body>
</html>

The code above is rendered as follows: