如何在画布上使运动呈正弦曲线?

问题描述 投票:0回答:1

我希望使点的线性运动呈正弦曲线,以便在边缘减慢直至停止,并在中间改变方向并加速。这是我的尝试。

let q = 51;
let x = 100;
let chang = 4;
let radiu = 20;
function motion(){
  requestAnimationFrame(motion);
  ctx3.beginPath();
  ctx3.fillStyle = "white";
  ctx3.fillRect(0,0,canvas3.width,canvas3.height);
  ctx3.fillStyle = "blue";
  ctx3.arc(x * Math.sin(q), 100, radiu, 0, 2 * Math.PI);
  ctx3.fill();
  ctx3.closePath();
  if(x + radiu > 200 || x - radiu < 50 ){
    chang=-chang;
  }
  x += chang;
  q=+1.0;
  //q+=0.1;
}
javascript trigonometry
1个回答
0
投票

您可能需要自定义缓动函数,例如:

sineX(t) = sin(t * PI / 2);

接受常数时间

t
并返回以弧度为单位的正弦值。
将结果值乘以偏移量以获得前后运动所需的 X 位置。如果画布宽度是(默认)300px,初始球的
x
是 150,那么数学就是
newX = x + sine * (x - rad)

const easeSin = (t) => Math.sin(t * Math.PI / 2);

const ctx = document.querySelector("canvas").getContext("2d");

let rad = 20;
let x = 150;
let t = 0; // linear time

const motion = () => {
  
  t += 0.02; // increment time
  const sine = easeSin(t); // here you have your sine easing
  
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(x + sine * (x - rad), 100, rad, 0, 2 * Math.PI);
  ctx.fill();
  ctx.closePath();

  requestAnimationFrame(motion);
};

motion();
canvas {
  background: #eee;
}
<canvas></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.