我是 HTML5 新手,基本上使用的代码结构类似于此处http://www.html5canvastutorials.com/advanced/html5-canvas-start-and-stop-an-animation/
根据 Paul Irish 的说法,当使用 requestAnimationFrame() 在选项卡之间切换时,动画会自动暂停
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
但是在第一个示例中,它不会暂停而是继续移动,并且有时在我们切换浏览器选项卡时也会消失。我发现了一个动画确实可以完美运行的示例。
如何修改代码以使动画不会在选项卡切换时继续?
function animate(lastTime, myRectangle, runAnimation, canvas, context) {
if(runAnimation.value) {
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
// pixels / second
var linearSpeed = 100;
var linearDistEachFrame = linearSpeed * timeDiff / 1000;
var currentX = myRectangle.x;
if(currentX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
var newX = currentX + linearDistEachFrame;
myRectangle.x = newX;
}
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// draw
drawRect(myRectangle, context);
// request new frame
requestAnimFrame(function() {
animate(time, myRectangle, runAnimation, canvas, context);
});
}
}