簡體   English   中英

如何停止畫布跳動畫

[英]How to stop canvas jumping animation

我有一個畫布動畫,您可以在這里看到。

我注意到,一段時間(約25秒)后觀看動畫,動畫就會開始跳來跳去。 我正在努力弄清楚如何使它成為一種恆定的流體運動?

代碼如下:

<canvas id="canvas"></canvas>

var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
canvas.width = parseInt(getComputedStyle(canvas).width);
canvas.height = parseInt(getComputedStyle(canvas).height);

var P = 4;
var A = 4;

function draw(shift) {
   var w = canvas.width;
   var h = canvas.height;
   shift = shift >= 500*Math.PI ? shift - 100*Math.PI : shift;
   ctx.clearRect(0, 0, w, h);
   var grd = ctx.createLinearGradient(0, 0, w, h);
   grd.addColorStop(0, "#4a8bf5");
   grd.addColorStop(1, "#f16b55");
   ctx.strokeStyle = grd;

   ctx.lineCap = "round";
   for (var i = 0; i < w; ) {
      var _A = Math.abs(A*Math.cos(2*i));
      ctx.beginPath();
      var pos = Math.exp(-_A * i / w) * Math.sin(P * Math.PI * (i + shift) / w);
      pos *= h / 2;
      var lw = Math.exp(-_A * i / w) * Math.sin(3 * Math.PI * (i - shift) / w) * 2;
      ctx.lineWidth = (lw)+1;
      ctx.lineTo(i, h / 2 - pos);
      ctx.closePath();
      ctx.stroke();
      i += 1;
   }

   window.requestAnimationFrame(function(){
      draw(shift + 1);
   });
}
draw(0);

解決方案是確保移位的變化導致sin()參數變化2π的倍數。

給定

Math.sin((i + shift) / (w / P))

這可以使用類似的方法完成

if (shift > 500) shift -= 2 * Math.PI * (w / P);

此處的第二個sin()參數sin()線寬sin()仍然會有跳躍。 為避免這種情況,必須將shift減少一個數字,該數字使兩個自變量都更改為2π的倍數(如果願意,則為LCM)。

 var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); canvas.width = parseInt(getComputedStyle(canvas).width); canvas.height = parseInt(getComputedStyle(canvas).height); var P = 10; var A = 4; var shift = 0; function draw() { var w = canvas.width; var h = canvas.height; shift += 1; if (shift > 500) shift -= 2 * Math.PI * (w / P); shift_el.innerHTML = shift; ctx.clearRect(0, 0, w, h); var grd = ctx.createLinearGradient(0, 0, w, h); grd.addColorStop(0, "#4a8bf5"); grd.addColorStop(1, "#f16b55"); ctx.strokeStyle = grd; ctx.lineCap = "round"; for (var i = 0; i < w;) { var _A = Math.abs(A * Math.cos(2 * i)); ctx.beginPath(); var pos = Math.exp(-_A * i / w) * Math.sin((i + shift) / (w / P)); pos *= h / 2; var lw = Math.exp(-_A * i / w) * Math.sin(3 * Math.PI * (i - shift) / w) * 2; ctx.lineWidth = (lw) + 1; ctx.lineTo(i, h / 2 - pos); ctx.closePath(); ctx.stroke(); i += 1; } window.requestAnimationFrame(draw); } draw(); 
 body { background: #ffffff; padding: 0; margin: 0; } canvas { height: 200px; width: 100%; } #shift_el { position: absolute; top: 0 } 
 <canvas id="canvas"></canvas> <div id="shift_el"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM