Why canvas stop clearing rectangle?

Viewed 130

I try to animate simple object in canvas and it works at start but after some time it stops to clear rectangles and just continue to fill new rectangles. At least i think it stop clearing maybe is something else. Can anyone help me? There are no console errors.

var canvas = document.querySelector('canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var c = canvas.getContext('2d');

var x=100;
function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0,0,window.innerHeight,window.innerWidth);
    c.beginPath();
    c.fillRect(x,100,100,100);
    x+=2;
}
animate();
body{
    margin: 0;
}
canvas{
    background: orange;
}
<canvas></canvas>

2 Answers

As pointed out by @Al.G in a comment, your height and width parameters are reversed in the clearRect() call. Swapping them c.clearRect(0, 0, window.innerWidth, window.innerHeight); will fix the problem.

I generally clear with canvas.width and canvas.height rather than non-canvas properties such as window.innerWidth and window.innerHeight since the canvas properties will always match its dimensions, reduce dependency on external/global variables and don't require thought beyond that.

var canvas = document.querySelector('canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var c = canvas.getContext('2d');
var x = 100;

function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.beginPath();
    c.fillRect(x, 100, 100, 100);
    x += 2;
}

animate();
body {
    margin: 0;
}
canvas {
    background: orange;
}
<canvas></canvas>

I will only add this here because the accepted answer fixed your problem accidentally.

The problem is that your reversed the parameters of clearRect;

You did:

c.clearRect(0,0,window.innerHeight,window.innerWidth);

While the answer was:

c.clearRect(0,0,window.innerWidth,window.innerHeight); 
Related