Skip to content Skip to sidebar Skip to footer

Canvas Image Leaves Weird Trail When Moving Left

I have an HTML5 Canvas where I need to move 2 copies of main object to right and left. Right side seems to be working fine, but left one starts to leave weird greenish trail. jSfid

Solution 1:

You need to clear the canvas in your fDrawRect function:

    function fDrawRect() {
        ctx.clearRect(0, 0, c.width, c.height); //Clear canvas
        ctx.beginPath();
        ctx.fillStyle = "red";
        ctx.rect(5, 5, 80, 60);
        ctx.fillRect(5, 5, 80, 60);
        ctx.stroke();
        ctx.beginPath();
        ctx.fillStyle = "blue";
        ctx.rect(85, 5, 80, 60);
        ctx.fillRect(85, 5, 80, 60);
        ctx.stroke();
        ctx.beginPath();
        ctx.fillStyle = "yellow";
        ctx.rect(165, 5, 80, 60);
        ctx.fillRect(165, 5, 80, 60);
        ctx.stroke();
    }

Solution 2:

Problem

When you attempt to clear the canvas in the beginning of playAnimation (using ctx.clearRect(0, 0, cWidth, cHeight)), you don't clear the entire area visible in the canvas.

Proof: If you draw a rect to cover the area you clear in playAnimation, you see that it does not start in the upper left corner like it should (fiddle).

The reason it does not work is this line, that translates the context once before you start rendering:

ctx.translate(450, 150);

When you remove it, you see that the the entire visible area is cleared (fiddle). However, now you don't get the name in the middle of the canvas.

Solution

The solution is to do the translation at the beginning of each playAnimation(), and to undo the translation at the end of the function (fiddle).


Post a Comment for "Canvas Image Leaves Weird Trail When Moving Left"