简体   繁体   English

我无法使用 setInterval 循环移动组件

[英]i can't loop moving component with setInterval

i tried make looping component using setInterval, but its not working, i'm new to canvas js so please help me我尝试使用 setInterval 制作循环组件,但它不起作用,我是 canvas js 的新手,所以请帮助我

so i want to make the function keep executing using setInterval所以我想让 function 继续使用 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这是 html 代码

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

The full solution, including @evolutionxbox comment about the setInterval that is not needed:完整的解决方案,包括关于不需要的 setInterval 的@evolutionxbox 评论:

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

Replace代替

setInterval(component, 100) 

for为了

component()

or Remove the requestAnimationFrame inside the function.或删除 function 内的 requestAnimationFrame。

You can do the render with requestAnimationFrame or with setInterval but not both.您可以使用 requestAnimationFrame 或 setInterval 进行渲染,但不能同时使用两者。

Why is requestAnimationFrame better than setInterval or setTimeout 为什么 requestAnimationFrame 比 setInterval 或 setTimeout 更好

RequestAnimationFrame will make your function be called each time the browser can. RequestAnimationFrame 将使您的 function 每次浏览器都可以调用。 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)因此,您每 100 毫秒执行一次 function 并添加它以尽快再次执行(每 100 毫秒您复制 function 将被调用的时间)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM