An example of the new canvas resetTransform function

Share RGraph:  

This article shows you an example of the new HTML5 canvas resetTransform function (although it won't immediately be available in all browsers or browser versions)

Warning: This example currently (September 2013) only works on recent Chrome releases.

If you use the transform() function then you've probably already noticed that multiple calls to it are additive - ie if you call it multiple times the transformations are added to whatever the current transformation is. For example if you use the transform() function to do a translate and then use it a second time to translate then the result would be as if you had translated once with the amounts summed together - ie two translates of (5,5) would be like doing one translate of (10,10).

If you prefer you can use the setTransform() function instead in which case the transformation matrix is set to whatever you provide. But now you can also use the function resetTransform() to set the transformation matrix back to the default. Some sample code follows:

    var canvas = document.getElementById("cvs");
    var context = canvas.getContext('2d');
    // Translate by 5,5
    // Translate by another 5,5
    // Reset the transform

Fallback when it's not available

Because it's a new function support for it will not be guaranteed - so here's something you can do in case the resetTransform function is not available:

if (!context.resetTransform) {
    context.resetTransform = function ()

Related pages