圈中圈运动效果

代码语言:html

所属分类:动画

代码描述:圈中圈运动效果

代码标签:

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<style>
body {
  background-color: #111;
}

canvas {
  display: block;
  margin: 0 auto;
}
</style>

</head>
<body translate="no">
<canvas height="320" id="js-canvas" width="320"></canvas>

<script>
const cycleDuration = 60 * 4; // time it takes for an orb pair to complete half an orbit

setTimeout(() => {
  const canvasEl = document.getElementById('js-canvas');
  const { width, height } = canvasEl;
  const canvasCtx = canvasEl.getContext('2d');
  const interpolator = createInterpolator(0, Math.PI, 1); // only does a half circle because the orb pairs shouldn't immediately swap back
  const numberOfOrbs = 12; // number of orb pairs
  animate(0, canvasCtx, width, height, interpolator, numberOfOrbs);
}, 0);

function animate(iteration, ctx, width, height, interpolator, count) {
  ctx.clearRect(0, 0, width, height);
  renderCollection(iteration, ctx, width, height, interpolator, count);
  requestAnimationFrame(() => {
    animate(iteration + 1, ctx, width, height, interpolator, count);
  });
}

function renderCollection(iteration, ctx, width, height, interpolator, count) {
  const radius = (Math.min(width, height) - 20) / 2 * 0.65; // just to add some margin, so orbs don't go off screen during orbit
  const stepSize = Math.PI * 2 / count;
  const x = width / 2;
  const y = height / 2;
  Array(...Array(count)).forEach((_, index) => {
    const pairHeading = index * stepSize;
    const pairX = x + Math.cos(pairHeading) * radius;
    const pairY = y + Math.sin(pairHeading) * radius;
    const offset = index * (cycleDuration / count); // staggers the start time of the orbits, this is why everything doesn't orbit in unison
    const t = Math.max(0, Math.min(1, (iteration + cycleDuration - offset) % cycleDuration / (cycleDuration / 3))); // where the magic happens
    renderOrbPair(ctx, pairX, pairY, radius * 0.4266, 12, width, height, interpolator, pairHeading, t); // 0.4266 is a magic number t.........完整代码请登录后点击上方下载按钮下载查看

网友评论0