2016-05-02 5 views
0

キャンバスを使用してパスの一部をアニメーション化しようとしています。基本的に私は3つのリンクを通る直線を持っています。リンクの上にマウスを置くと、リンクの後ろのパスのセクションが正弦波にアニメートされます。キャンバスを使用してパスの一部をアニメーション化する

私は、正弦波の形状にパス全体をアニメーション化問題はありませんが、それはパスのセクションをアニメーションに来るとき、私は途方に暮れてよ:(

私は参照画像を添付しました以下、それは私が達成しようとしているかのアイデアを得ることができる。以下

reference image

私は、現在のパスをアニメーション化するために使用しているコードのjsfiddleである。私はキャンバスのnoobだので、私を許してそれがひどい場合...

https://jsfiddle.net/9mu8xo0L/

、ここのコードです:

class App { 

     constructor() { 

     this.drawLine(); 

     } 

     drawLine() { 

     this.canvas = document.getElementById('sine-wave'); 
     this.canvas.width = 1000; 

     this.ctx = this.canvas.getContext("2d"); 
     this.cpY = 0; 
     this.movement = 1; 
     this.fps = 60; 

     this.ctx.moveTo(0, 180); 
     this.ctx.lineTo(1000, 180); 
     this.ctx.stroke(); 

     this.canvas.addEventListener('mouseover', this.draw.bind(this)); 

     } 

     draw() { 

     setTimeout(() => { 

      if (this.cpY >= 6) return; 

      requestAnimationFrame(this.draw.bind(this)); 

      // animate the control point 
      this.cpY += this.movement; 

      const increase = (90/180) * (Math.PI/2); 
      let counter = 0; 
      let x = 0; 
      let y = 180; 

      this.ctx.beginPath(); 

      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); 

      for(let i = 0; i <= this.canvas.width; i += 6) { 

      this.ctx.moveTo(x,y); 

      x = i; 
      y = 180 - Math.sin(counter) * this.cpY; 

      counter += increase; 

      this.ctx.lineTo(x, y); 
      this.ctx.stroke(); 

      } 

     }, 1000/this.fps); 

     } 

    } 

答えて

1

単純に、直線として1/3を描く、三つの部分にラインの描画を分割する中間部分をアニメーション化し、最後の3分の1を追加しますが。

私は最初の1/3 +アニメーションをデモンストレーションし、演習として最後の1/3を残します(stroke()もループ外に移動され、セグメントごとにオーバードローされません)。リファクタリングと最適化の余地がありますここで私は、この例であることに対処していない - K3N @迅速な回答を

let x = this.canvas.width/3; // start of part 2 (animation) 
    let y = 180; 

    this.ctx.beginPath(); 

    this.ctx.clearRect(0, x, this.canvas.width, this.canvas.height); 

    // draw first 1/3 
    this.ctx.moveTo(0, y); 
    this.ctx.lineTo(x, y); 

    // continue with part 2 
    for(let i = x; i <= this.canvas.width; i += 6) { 
    x = i; 
    y = 180 - Math.sin(counter) * this.cpY; 

    counter += increase; 

    // add to 2. segment 
    this.ctx.lineTo(x, y); 
    } 

    // stroke line 
    this.ctx.stroke(); 

Modified fiddle

+0

感謝を。これは私が探していたものですが、唯一の問題はセクションがシームレスではないということです。この更新されたフィドルを見て、私の言いたいことを見てください。これは私が実際には分かっていなかった... https://jsfiddle.net/9mu8xo0L/3/ – Ashmore11

+0

@ Ashmore11あなたは2/3に線を伸ばしてyを強制し、同じyで最後の線分を描くことができました。フィドルを更新しました:https://jsfiddle.net/epistemex/9mu8xo0L/4/ – K3N

関連する問題