setInterval随着时间的流逝而变慢

Dev*_*Nub 2 javascript performance canvas setinterval

我刚刚开始学习JavaScript。我的问题是,网站在几秒钟后变慢。我正在使用setinterval来“勾选”屏幕上的内容,我觉得这可能是问题的原因。

这是我的代码:

var r = [];
var ctx;

function init() {
    ctx = document.getElementById("canvas").getContext("2d");
    for(var i = 0; i < 20; i++) {
        var x = Math.floor(Math.random() * (ctx.canvas.width - 20)) + 10;
        var y = Math.floor(Math.random() * (ctx.canvas.height - 20)) + 10;
        r.push(new Rect(x,y, 10, 10, ctx));
    }
window.setInterval(tick,10);
window.setInterval(draw,10);
} 

function tick() {
    for(var i = 0; i < r.length; i++) {
        r[i].tick();
    }
} 

function draw() {
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
    for(var i = 0; i < r.length; i++) {
        r[i].draw();
        }
        ctx.lineWidth = 5;
        ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
        ctx.stroke();
} 
Run Code Online (Sandbox Code Playgroud)

这是另一堂课:

class Rect {
    constructor(x, y, width, height, ctx) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.cxt = ctx;
        this.xVel = 2.5;
        this.yVel = 2.5;

        if (Math.random() < 0.5) {
            this.xVel = -this.xVel;
        }

        if (Math.random() < 0.5) {
            this.yVel = -this.yVel;
        }
    } 

    tick(){
        this.x += this.xVel;
        this.y += this.yVel;
        if (this.x + this.width >= ctx.canvas.width | this.x <= 0){
            this.xVel = -this.xVel;
        }
        if (this.y + this.height >= ctx.canvas.height | this.y <= 0){
        this.yVel = -this.yVel;
        }
    }

    draw() {
        ctx.fillRect(this.x,this.y,this.width,this.height);
    } 
} 
Run Code Online (Sandbox Code Playgroud)

那么,此问题的确切原因是什么,我该如何解决?

您可以在此处下载文件:https : //drive.google.com/file/d/1pg4ASPvjbo2ua_7cCvQvzucLgbegtiw6/view?usp=sharing

小智 5

这个问题在您的绘图功能中。

画布会记住所有绘制的线条,随着时间的流逝,它会使动画速度变慢。

解决方案是通过调用ctx.beginPath()重置绘制的线条列表

function draw() {
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    for (var i = 0; i < r.length; i++) {
        r[i].draw();
    }
    ctx.beginPath()
    ctx.lineWidth = 5;
    ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.stroke();
}
Run Code Online (Sandbox Code Playgroud)