Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why canvas stop clearing rectangle?

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>
like image 480
Danilo Ivanovic Avatar asked Oct 17 '22 13:10

Danilo Ivanovic


People also ask

How do you delete a rectangle in canvas?

The clearRect() method in HTML canvas is used to clear the pixels in a given rectangle.

How do you clear a whole canvas?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.

How do I reset my canvas?

From the course navigation menu, select Settings. In the "Settings" sidebar at the right, select Delete All Course Content. You will be prompted to confirm. To proceed, click Reset Course Content, or click Cancel to cancel.


1 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>
like image 124
ggorlen Avatar answered Oct 20 '22 05:10

ggorlen