Javascript 控制多个画布动画

Javascript 控制多个画布动画,javascript,html,canvas,Javascript,Html,Canvas,是否可以挂接到已绘制的画布动画中? 我试图创建3个独立的轨迹,必须由“开始”和“停止”按钮控制,但当按下第一个画布的“开始”按钮时,它会使最后一个画布运行 这就是我目前所拥有的 class Animation{ constructor(){ this.options = { left : 0, animate : false } let tracks = $('.line'); let self = this; tracks.

是否可以挂接到已绘制的画布动画中? 我试图创建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();

您的代码存在范围问题,您必须确保每个轨迹都独立于其构造函数运行

这就是我确保信息对于给定的轨迹/父元素是完全独立的地方

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();
需要完成范围和对象处理