是否可以挂钩已经绘制的Canvas动画? 我正在尝试创建3个单独的轨道,必须由“开始”和“停止”按钮控制,但是当按下第一个画布的“开始”按钮时,它会使最后一个画布运行。
这是我到目前为止所做的。
class Animation{
constructor(){
this.options = {
left : 0,
animate : false
}
let tracks = $('.line');
let self = this;
tracks.each(function(){
self.startbtn = $(this).find('button.start');
self.stopbtn = $(this).find('button.stop');
self.canvas = $(this).find('canvas').get(0);
self.canvas.width = 1000;
self.canvas.height = 30;
self.ctx = self.canvas.getContext('2d');
self.draw(self.canvas,self.ctx);
self.startbtn.bind('click',() => {
self.options.animate = true;
self.draw(self.canvas,self.ctx);
})
});
}
draw(c,ctx){
ctx.clearRect(0,0,c.height,c.width);
ctx.fillRect(this.options.left,0,1,30);
if(this.options.animate){
requestAnimationFrame(() => {
console.log('done');
this.options.left += 1;
console.log(this.options.left)
this.draw(c,ctx);
});
}
}
}
new Animation();
答案 0 :(得分:2)
您的代码存在范围问题,您必须确保每个轨道与其构造函数分开运行。
这是我确保信息完全独立于给定的track / parent元素的地方。
this.options = *set*;//left and animate separate for own process
this.node = *set*;//nodes for each track
this.ctx = *set*;//draw command context set at the parent
this.draw = *set*;//draw function moved to track
以下是对您的代码的完整修改:
class Animation{
constructor(){
var tracks = $('.line');
var self = this;
tracks.each(function () {
this.options = {//options seperate to parent track node
left: 0,
animate: false
};
this.node = {//store child nodes for access
startbtn: $(this).find('button.start'),
stopbtn: $(this).find('button.stop'),
canvas: $(this).find('canvas').get(0)
};
this.node.canvas.width = 1000;
this.node.canvas.height = 30;
this.ctx = this.node.canvas.getContext('2d');
this.node.startbtn.bind('click',() => {// () => parentNode instantiation
this.options.animate = true;
this.draw(this.node.canvas, this.ctx);
});
this.draw = self.draw;
});
}
draw(c,ctx){
parent = c.parentNode;
ctx.clearRect(0,0,c.height,c.width);
ctx.fillRect(parent.options.left,0,1,30);
if(parent.options.animate){
requestAnimationFrame(() => {
console.log('done');
parent.options.left += 1;
console.log(parent.options.left)
parent.draw(c,ctx);
});
}
}
}
new Animation();
需要完成范围和对象处理。