Observe that you call obj.draw as :
<button onclick="obj.draw()
The first time obj.draw is called, the context is different than when it called by requestAnimationFramemultiple times, as a callback function before the repaint.
So try by saving this in a variable which is outside the scope of the callback function.
Something like :
var obj = { //... draw: function () { var sender = this; var draw = function () { document.getElementById(sender.id).style.left = (sender.speed++) + 'px'; window.requestAnimationFrame(draw); } draw(); } }
Here is an updated demo of how this would look like.
http://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword
本文探讨了在JavaScript中利用requestAnimationFrame优化对象绘制的过程。通过将对象引用保存到变量外,确保每次调用draw函数时都能正确访问最新的状态。演示了一个更新后的示例,展示如何在多个回调函数调用间保持正确的渲染逻辑。

被折叠的 条评论
为什么被折叠?



