Home > Blockchain >  i can't loop moving component with setInterval
i can't loop moving component with setInterval

Time:08-10

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>

CodePudding user response:

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()

CodePudding user response:

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)

  • Related