Falcon80 Logo
Using the transform matrix on canvas

The setTransform() method is slightly difficult to understand and requires a knowedge of matrix representation of pixels and matrix manipulation. If you already know how to use the transform() method, it is easier. Otherwise, for a basic understanding of both concepts, williamette.edu has a good tutorial.

This is how the setTransform() method works. It will first reset the current transformation matrix to the identity matrix. What is an identity matrix?

The parameters of the setTransform() method are then passed to the transform() method resulting in the transformation matrix specified by the setTransform() method being be multiplied by the identity matrix.

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var canvas = document.getElementById("canvas");
if (canvas.getContext) {

var ctx = canvas.getContext("2d");
//Load a new image and draw it at 25,0)
var flower = new Image();
flower.src = "flower.png";
ctx.drawImage(flower,25,0);

// Let's do a translation and move the image 200 pixels in the x-direction and 20 pixels // in the y-direction
var dx = 200;
var dy = 20;
ctx.setTransform(1,0,0,1,dx,dy);
ctx.drawImage(flower,25,0);

}
}
  </script>
  <title>Translating an image on canvas</title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
Try Code