The setTransform() and transform() functions use "matrix" calculations to transform the canvas. What does this mean? In practice it's a combination of the scale() and translate() functions and also allows the skewing of the canvas. So if you don't need skewing then you can quite realistically get by with the scale() and translate() functions. A transform looks like this:
context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
And these arguments are:
The difference between the two functions is that the transform() function adds to whatever transformations that you've done before. So this:
context.transform(1,0,0,1,10,10); context.transform(1,0,0,1,10,10); context.transform(1,0,0,1,10,10);
Is the same as doing this:
And if you do another setTransform(1,0,0,1,30,30) call - it remains the same.
All browsers suppport the transform and setTransform functions - though in the example below not all browsers support the HTML5 range input (the slider) - so you may see text inputs instead.
This example allows you to see the effect of each type of transformation. Keep in mind that the order of the arguments is not immediatly obvious - so the appropriate code is shown below the chart.
At first the two functions may seem similar. However when you start to do multiple transformations the difference may become apparent. The transform() function ADDS the transformation that you give it to whatever the current transform is. Whereas the setTransform() SETS it to whatever you give it.
context.transform(1,0,0,1,5,5); // A translate by [5,5] context.transform(1,0,0,1,5,5); // A translate by [5,5] context.transform(1,0,0,1,5,5); // A translate by [5,5] context.transform(1,0,0,1,5,5); // A translate by [5,5]
Has the same result as this:
context.setTransform(1,0,0,1,20,20); // A translate by [20,20]
Like the example shows, the scale part of the transformation (or the stand-alone scale function) can be used like the example below to scale the canvas in the appropriate direction so that a standard circle becomes an ellipse.
<script> context = document.getElementById("cvs").getContext('2d'); context.transform(1.5,0,0,1,0,0); context.beginPath(); context.fillStyle = 'red'; context.lineWidth = 4; context.arc(75,50,35,0,2 * Math.PI, true); context.stroke(); context.fill(); </script>
There other transformation functions that aren't covered by the transform function such as: