【发布时间】:2019-10-09 09:31:46
【问题描述】:
我正在尝试在 Vue 中实现this post,它可以绘制并动画化一个简笔画。
draw(timestamp, wave) {
if(Date.now() < (timestamp+900)) return requestAnimationFrame(this.draw);
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
context.beginPath();
context.fillStyle = "black"; // #000000
context.arc(200, 50, 30, 0, Math.PI * 2, true);
context.fill(); //fill the circle
context.beginPath();
context.lineWidth = 6;
context.stroke();
//body
context.beginPath();
context.moveTo(200, 80);
context.lineTo(200, 180);
context.strokeStyle = "black";
context.stroke();
//arms
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 100);
context.lineTo(150, 130);
if(wave) {
context.moveTo(200, 100);
context.lineTo(250, 130);
wave = false;
}
else {
context.moveTo(200, 100);
context.lineTo(250, 70);
wave = true;
}
context.stroke();
//legs
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 180);
context.lineTo(150, 280);
context.moveTo(200, 180);
context.lineTo(250, 280);
context.stroke();
timestamp = Date.now();
requestAnimationFrame(this.draw);
}
},
mounted: function () {
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // get Canvas Context object
let timestamp = Date.now();
let wave = false;
this.draw(timestamp, wave);
}
如果我在 mounted 方法中执行整个 draw 方法,它就可以工作。但是当我将 draw 移到它自己的方法时,如上所示,它失败了。
我知道它失败了,因为在运行上面的代码时,if(Date.now() < (timestamp+900)) 行总是返回 false。但我不确定为什么会这样,或者有什么区别。
如何让这个画布动画化?
【问题讨论】:
-
它可能不知道
context是什么,因为它是在你mounted函数的范围内定义的,并没有传入draw函数中。 -
@Bryan 谢谢!我没有收到任何错误,它绘制了图形,只是没有为手臂设置动画
-
您能澄清一下您的绘图函数是计算属性还是方法?
标签: javascript vue.js vuejs2 html5-canvas