我刚开始学习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();
}
这是另一个类:
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);
}
}
那么这个问题的确切原因是什么,我该如何解决?
您可以在此处下载文件:https://drive.google.com/file/d/1pg4ASPvjbo2ua_7cCvQvzucLgbegtiw6/view?usp=sharing
<>
并创建一个可以运行的代码片段。 - undefinedsetInterval
,而是这样做:setInterval(function(){tick();draw();},10);
。 - user1636522