2016-08-17 8 views
3

すでに描画されているキャンバスアニメーションにフックすることはできますか? 「スタート」ボタンと「停止」ボタンで制御する必要がある3つの別々のトラックを作成しようとしていますが、最初のキャンバスの「開始」ボタンを押すと、最後のキャンバスが実行されます。複数のキャンバスアニメーションを制御する

See current codepen progress

これは私がこれまで持っているものです。

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(); 

答えて

2

コードに範囲の問題があり、各トラックがそのコンストラクタとは別に動作していることを保証する必要がありました。

ここでは、情報が特定のトラック/親要素に対して完全に独立していることを確認しました。ここで

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(); 

スコープとオブジェクトの処理が行われるために必要な。

http://codepen.io/anon/pen/JKzBLK

+0

パーフェクト、魔法のように動作します! –

関連する問題