这是我遇到的奇怪的事情之一。
基本上,在我的网站上,有一堆旋转的形状。每个旋转形状在第一次被调用时都会设置一个超时,以使其旋转。每当访问者点击网页时,这些形状就会被清除并再次随机生成。
问题是在第二次点击时,它们旋转得更快一些。在第三次点击时甚至更快,到第四次点击时,它们旋转得如此之快,以至于它们变得超级波涛汹涌和不流畅。
当使用 chrome://flags FPS 计数器观看网站时,它会以 60 fps 的速度开始,然后到第四次或第五次点击时,它将在 20 到 50 fps 之间跳跃。
代码的缩写部分如下:
//creates timeout variable OUTSIDE the timeout function, so it can be cleared
var t;
var speedRandom;
function getRandSpeed(){
var randomSpeed = (Math.random()*.01);
if (randomSpeed<=.001){
randomSpeed=.001;
}else if(randomSpeed>=.005){
randomSpeed=.005;
}
console.log(randomSpeed);
if (rightSpin==0){
speedRandom=randomSpeed;
rightSpin=1;
}else{
speedRandom=-randomSpeed;
rightSpin=0;
}
}
objs[whichImg].speed = speedRandom;
function rotateDrawing(whichImg){
//This is the function that centers the object
centerImg(whichImg);
//translates the object to the centered point (different for each frame)
objs[whichImg].ctx.translate(objs[whichImg].centeredX,objs[whichImg].centeredY);
//rotates to the correct angle
objs[whichImg].ctx.rotate(objs[whichImg].angle);
//draws the image
objs[whichImg].ctx.drawImage(objs[whichImg].image,0,0,objs[whichImg].height,objs[whichImg].width);
//adds to the angle of the object
objs[whichImg].angle+=objs[whichImg].speed;
t=setTimeout(function(){rotateDrawing(whichImg)},40);
}
//THE ABOVE CODE WILL BE EXECUTED FOR EVERY SHAPE (TOTAL AROUND 5)
//this is what is called when the screen is clicked
function destroy(){
functionThatClearsAllTheImages();
clearTimeout(t);
rotateDrawing(whichImg);
}
这段代码可能有一些漏洞,但它确实起作用,问题是在第五次点击后它是断断续续的。
如果有人需要,我可以添加更多代码,但任何建议都会非常有帮助!