猿问

使用 javascript 和 CSS 在曲线上制作 sin 和 cos 动画

我正在尝试使用 sin 和 cos 为 CSS 图像设置动画以在此形状上移动。无法使 CSS 图像在弯曲的贝塞尔线上移动。


有人可以协助如何使用 sin 或 cos 因此,如果添加了 CSS 对象,它会沿着这样的线平滑移动吗?


这是我尝试使用javascript中的sin和cos数学使黄色圆圈在该行上移动的代码。


谢谢


var field = document.getElementById("field");

  var ball = document.getElementById("ball");

  var ball2 = document.getElementById("ball2");


  var maxX = field.clientWidth - ball.offsetWidth;

  var maxY = field.clientHeight - ball.offsetHeight;


  var duration = 5; // seconds

  var gridSize = 50; // pixels


  var start = null;


  function step(timestamp) {

    var progress, x, y, y2;

    if (start === null)

      start = timestamp;


    progress = (timestamp - start) / duration / 1000; // percent


    x = progress * maxX / gridSize; // x = ƒ(t)

    y = 2 * Math.sin(x); // y = ƒ(x)

    y2 = 2 * Math.cos(x);


    ball.style.left = ball2.style.left = Math.min(maxX, gridSize * x)

        + "px";

    ball.style.bottom = maxY / 2 + (gridSize * y) + "px";

    ball2.style.bottom = maxY / 2 + (gridSize * y2) + "px";


    if (progress >= 1)

      start = null; // reset to start position

      requestAnimationFrame(step);

  }

  requestAnimationFrame(step);

#field {

  position: absolute;

  height: 300px;

  width: 300px;

  z-index: 50;

  top: 20px;

  left: 20px;

}


#ball {

  position: absolute;

  left: 0;

  bottom: 50%;

  width: 40px;

  background: yellow;

  z-index: 5;

  height: 40px;

  border-radius: 200px;

}


#ball2 {

  position: absolute;

  left: 0;

  bottom: 50%;

  width: 20px;

  height: 20px;

  /*background: silver;*/

  border-radius: 100px;

}

<div id="field">

  <div id="ball"></div>

  <div id="ball2"></div>

</div>


暮色呼如
浏览 243回答 1
1回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答