css js 轨迹动画

南山 7个月前 168浏览 0评论

在网站设计中,轨迹动画已经成为了让用户感受更好的重要因素。通过使用css和js,我们可以实现各种各样的轨迹动画效果。

// CSS实现轨迹动画
.circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ff0000;
  position: relative;
  animation: circle 3s infinite;
}

@keyframes circle {
  0% {
    top: 0px;
    left: 50px;
  }
  25% {
    top: 100px;
    left: 50px;
  }
  50% {
    top: 100px;
    left: 150px;
  }
  75% {
    top: 0px;
    left: 150px;
  }
  100% {
    top: 0px;
    left: 50px;
  }
}

// JS实现轨迹动画
let circle = document.querySelector('.circle');
let position = {x: 0, y: 0};
let target = {x: 150, y: 150};
let animate = gsap.to(position, {
  duration: 3,
  x: target.x,
  y: target.y,
  onUpdate: () => {
    circle.style.left = position.x + 'px';
    circle.style.top = position.y + 'px';
  },
  repeat: -1
});

通过使用CSS中的关键帧动画,我们可以实现各种各样的轨迹动画效果。这可以是非常简单的动画,也可以是更复杂的动画,根据需求去定义不同的关键帧就可以了。

而JS的TweenMax或者gsap库可以让我们更加自由,可以通过使用JS计算位置来动态的改变元素的位置,从而实现各种各样的效果。

总之,CSS和JS可以相互配合,实现各种各样的轨迹动画效果,让网站更加生动有趣。