An example of the new canvas resetTransform function

Posted on 13th September 2013
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:

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

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 ()
    {
        this.setTransform(1,0,0,1,0,0);
    }
}

Related pages