0

i tried make looping component using setInterval, but its not working, i'm new to canvas js so please help me

so i want to make the function keep executing using setInterval

const canvas = document.getElementById("canvas")          
const context = canvas.getContext("2d")            
canvas.width = 400                 
canvas.height = 500                        
let y = 50

function component() {
    context.clearRect(0, 0, canvas.width, canvas.height)
    context.beginPath()
    context.fillStyle = 'blue'
    context.fillRect( 10, y, 20, 20)    
    context.closePath()  
    y += 1
    if(y >= 400) {
    context.clearRect(0, 0, canvas.width, canvas.height)
    }
    requestAnimationFrame(component)

}

setInterval(component, 100)

This is the html code

<style>
    #canvas{
        background-color: rgb(37, 24, 42);
    }
</style>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <center>
        <canvas id="canvas"></canvas>
        </center>
        <script src="app.js"></script>
</body>
</html>
  • You need to reset y to 50 when it reach the end of the canvas, so add `y = 50` in your `if(y >= 400) {` – Lk77 Aug 10 '22 at 12:19
  • Since you're using `requestAnimationFrame` I think you can remove the `setInterval`. Just call the function once `component()` – evolutionxbox Aug 10 '22 at 12:20

2 Answers2

0

Replace

setInterval(component, 100) 

for

component()

or Remove the requestAnimationFrame inside the function.

You can do the render with requestAnimationFrame or with setInterval but not both.

Why is requestAnimationFrame better than setInterval or setTimeout

RequestAnimationFrame will make your function be called each time the browser can. So you are executing every 100ms that function and adding it to be executed as soon as posible again (each 100ms you are duplicating the times that the function is going to be called)

Edoldin
  • 160
  • 6
-1

The full solution, including @evolutionxbox comment about the setInterval that is not needed :

const canvas = document.getElementById("canvas")
const context = canvas.getContext("2d")
canvas.width = 400
canvas.height = 500
let y = 50

function component() {
    context.clearRect(0, 0, canvas.width, canvas.height)
    context.beginPath()
    context.fillStyle = 'blue'
    context.fillRect( 10, y, 20, 20)
    context.closePath()
    y += 1
    if(y >= 400) {
        y = 50;
        context.clearRect(0, 0, canvas.width, canvas.height)
    }
    requestAnimationFrame(component)

}

component()
Lk77
  • 2,203
  • 1
  • 10
  • 15