Canvas How to - Transform back after scale and transform








Question

We would like to know how to transform back after scale and transform.

Answer


<!--from  w w  w . j a va  2  s. c  o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        drawReferenceDot(15, "blue");
        ctx.beginPath();
        // transform
        ctx.translate(100, 100);
        ctx.scale(2, 2);
        // draw
        ctx.rect(0, 0, 25, 25);
        ctx.fill();
        // un-transform (in exactly reverse order)
        ctx.scale(0.5, 0.5);
        ctx.translate(-100, -100);

        drawReferenceDot(8, "red");
        function drawReferenceDot(radius, color) {
            ctx.beginPath();
            ctx.fillStyle = color;
            ctx.arc(50, 50, radius, 0, Math.PI * 2, false);
            ctx.fill();
        }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

The code above is rendered as follows: