【发布时间】:2018-07-26 18:04:17
【问题描述】:
我有一个需要一些坐标和持续时间数据的类。我想用它来为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);
}
我可以把它变成一种方法,用this 替换circleLine。这在第一次运行时运行良好,但是当它第二次调用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是如何以及在哪里定义的? -
distancePerFrame()怎么样? -
我刚刚意识到我可以将
requestAnimationFrame定义为对象上的道具。 -
@icicleking 如果你丢失了
this,那也无济于事。幸运的是,这不是解决这个问题的唯一方法。
标签: javascript oop animation scope requestanimationframe