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>
The clearRect() method in HTML canvas is used to clear the pixels in a given rectangle.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With