Search code examples
htmlhtml5-canvas

How to clear HTML5 canvas after scale


I have a problem while i work with canvas. See below code.

HTML

<canvas id="canvas" width="400" height="400"></canvas>    
<input id="but" type="button" value="clear canvas" onclick="ClearCanvas()">

JS

can = document.getElementById('canvas');
ctx = can.getContext("2d");

ctx.fillStyle = 'rgb(205,190,245)';
ctx.fillRect(0, 0, can.width, can.height);

ctx.scale(0.4, 0.4);
ctx.fillStyle = 'rgb(105,180,235)';
ctx.fillRect(0, 0, can.width, can.height);

$("#but").click(function()
{
    var ctx = document.getElementById('canvas').getContext("2d");

    ctx.scale(1, 1);
    ctx.clearRect(0, 0, can.width, can.height);
});

While i click on "clear canvas" button, it is not clearing entire canvas. It is just clearing the portion that was scaled. How to clear whole canvas after did scaling?

You can catch this live in this FIDDLE

Note: No problem in FF.


Solution

  • Your line:

    ctx.scale(1, 1);
    

    Should read:

    ctx.scale(2.5, 2.5);
    

    Initially you reduced the scale from 1 to 0.4 which is 2.5 times smaller than the original scale. (1 / 0.4 = 2.5)

    Setting a scale to 1 will scale by 100% i.e no change.

    Other options are:

    • Replace ctx.scale(1, 1); with ctx.setTransform(1, 0, 0, 1, 0, 0);
    • Use Save() and Restore() link