我有一个类,它带有一些坐标和持续时间的数据。我想使用它来动画显示一个
这段内容也将被插入到类中,现在它只是一个辅助函数:
svg
。更明确地说,我想使用该数据在时间范围内更改svg
属性。我在类外使用了step
函数和requestAnimationFrame
。function step(timestamp) {
if (!start) start = timestamp
var progress = timestamp - start;
var currentX = parseInt(document.querySelector('#start').getAttribute('cx'));
var moveX = distancePerFrame(circleMove.totalFrames(), circleMove.xLine);
document.querySelector('#start').setAttribute('cx', currentX + moveX);
if (progress < circleMove.duration) {
window.requestAnimationFrame(step);
}
}
var circleMove = new SingleLineAnimation(3000, startXY, endXY)
var start = null
function runProgram() {
window.requestAnimationFrame(step);
}
我可以将其转换为一个方法,将circleLine
替换为this
。这在第一次运行时正常工作,但当它第二次调用this.step
回调时,我们就陷入了回调黑洞,对this
的引用被破坏了。使用旧的self = this
也不起作用,一旦我们跳进回调函数,this
就变成未定义的(我不确定为什么)。以下是其作为一个方法的代码:
step(timestamp) {
var self = this;
if (!start) start = timestamp
var progress = timestamp - start;
var currentX = parseInt(document.querySelector('#start').getAttribute('cx'));
var moveX = distancePerFrame(self.totalFrames(), self.xLine);
document.querySelector('#start').setAttribute('cx', currentX + moveX);
if (progress < self.duration) {
window.requestAnimationFrame(self.step);
}
}
有没有关于如何在对象内部保持“连线”的想法?
这是一段代码,大致上可以使用在类外定义的step
函数。
class SingleLineAnimation {
constructor(duration, startXY, endXY) {
this.duration = duration;
this.xLine = [ startXY[0], endXY[0] ];
this.yLine = [ startXY[1], endXY[1] ];
}
totalFrames(framerate = 60) { // Default to 60htz ie, 60 frames per second
return Math.floor(this.duration * framerate / 1000);
}
frame(progress) {
return this.totalFrames() - Math.floor((this.duration - progress) / 17 );
}
}
这段内容也将被插入到类中,现在它只是一个辅助函数:
function distancePerFrame(totalFrames, startEndPoints) {
return totalFrames > 0 ? Math.floor(Math.abs(startEndPoints[0] - startEndPoints[1]) / totalFrames) : 0;
}
点击按钮来...
function runProgram() {
window.requestAnimationFrame(step);
}
runProgram()
函数在何时何地被调用?SingleLineAnimation
是如何定义的,它定义在哪里? - zer00nedistancePerFrame()
怎么样? - zer00nerequestAnimationFrame
定义为对象上的一个属性。 - iciclekingthis
,那是没有帮助的。幸运的是,这不是破解这个难题的唯一方法。 - Alnitak