首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >canvas2d: cancelAnimationFrame不起作用

canvas2d: cancelAnimationFrame不起作用
EN

Stack Overflow用户
提问于 2021-08-01 19:20:50
回答 1查看 60关注 0票数 0

问题

一旦蜂窝中的每一项移动到其末端位置(动画从单击六边形上的开始),它就会触发stop()。到目前为止这是可行的。问题是,stop()是在无限循环中调用的(参见控制台日志记录stop),在我看来,cancelAnimationFrame工作得不太好。

目标

一旦蜂窝的每一个项目移动到它的结束位置,动画应该停止,因为没有任何移动无论如何。一旦你再次点击,每一个项目再次折叠到中间(完全相反的打开动画),有点像一个切换。

代码语言:javascript
复制
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext("2d");
const hexagonArray = [];

var raf;

const items = [
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
];

class Hexagon {
  constructor(heading, subheading, idx) {
    this.idx = idx;
    this.sixtyDeg = Math.PI * 2 / 6;
    this.radius = 80;
    this.gap = 1.9;
    this.fromX = canvas.width / 2;
    this.fromY = canvas.height / 2;
    this.toX = this.fromX + this.gap * this.radius * Math.sin(this.sixtyDeg * idx);
    this.toY = this.fromY + this.gap * this.radius * Math.cos(this.sixtyDeg * idx);
    this.x = this.fromX;
    this.y = this.fromY;
    this.frames = 100;
    this.frame = 0;
    this.speedX = this.toX / this.frames;
    this.speedY = this.toY / this.frames;
    this.isCurrent = false;
    this.heading = heading;
    this.subheading = subheading;
  }

  draw() {
    const { sixtyDeg, radius, x, y, idx } = this;
    // ctx.fillStyle = "red";
    // ctx.fillText(`no.${idx}`, x, y);
    ctx.beginPath();
    for (let i = 0; i < 6; i++) {
      ctx.lineTo(
        x + radius * Math.cos(sixtyDeg * i),
        y + radius * Math.sin(sixtyDeg * i)
      );
    }
    ctx.closePath();
    ctx.fill();
  }

  update(shouldOpen) {
    this.x = expEaseInOut(
      this.frame,
      this.fromX,
      this.toX - this.fromX,
      this.frames  
    );

    this.y = expEaseInOut(
      this.frame,
      this.fromY,
      this.toY - this.fromY,
      this.frames  
    );

    if (
      (shouldOpen ? this.frame < this.frames : this.frame > this.frames)
      && this.idx !== 0
    ) {
      this.frame = shouldOpen
        ? this.frame + 1  // open
        : this.frame - 1; // close
    } else if (this.idx !== 0) {
      stop();
    }

    this.draw();
  }

  toggle() {
    let toggle = false;
    this.update(!toggle);
    toggle = !toggle;
  }
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  hexagonArray.forEach((hexagon) => {
    hexagon.toggle();
  });
  raf = window.requestAnimationFrame(animate);
}

function stop() {
  console.log('stop');
  window.cancelAnimationFrame(raf);
}

canvas.addEventListener('click', function (event) {
  const {
    clientX,
    clientY
  } = event;

  hexagonArray.some((hexagon) => {
    const isInRange = (
      inRange(clientX, hexagon.x - hexagon.radius, hexagon.x + hexagon.radius)
      && inRange(clientY, hexagon.y - hexagon.radius, hexagon.y + hexagon.radius)
    );
    if (isInRange) {
      raf = window.requestAnimationFrame(animate);
      return true;
    }
  });
});

function init() {
  items.forEach(({ heading, subheading }, idx) => {
    hexagonArray.push(new Hexagon(heading, subheading, idx));
  });
  hexagonArray.forEach((hexagon) => {
    hexagon.draw();
  });
}

init();

/** -------------------------------------------------------------------------------- */
/** -------------------------------------------------------------------------------- */
/** -------------------------------------------------------------------------------- */

window.addEventListener('resize', function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  init();
});

function expEaseInOut(frame, initPos, distance, frames) {
  frame /= frames / 2;
  if (frame < 1) return distance/2 * Math.pow( 2, 10 * (frame - 1) ) + initPos;
  frame--;
  return distance/2 * ( -Math.pow( 2, -10 * frame) + 2 ) + initPos;
};

function inRange(n, min, max) {
  return ((n-min)*(n-max) <= 0);
}
代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script async src="index.js"></script>
  <title>canvas2d</title>
</head>
<body>
  <style>
    body {
      min-width: 100vw;
      min-height: 100vh;
      background-color: lightgray;
    }

    canvas {
      background-color: gray;
    }
  </style>
  <canvas
    width="440"
    height="440"
  ></canvas>
</body>
</html>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-01 23:29:12

实际上,问题是您在requestAnimationFrame之后再次调用它,因此它继续循环。

代码语言:javascript
复制
function animate() {

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // You're updating the 6 hexagons & calling "cancelAnimationFrame" in here
  hexagonArray.forEach((hexagon) => {
    hexagon.toggle();
  });

  // BUT... you call the animation again just after, so it keeps looping
  raf = window.requestAnimationFrame(animate);
}

如果在更新逻辑和绘图之前调用动画,它不会循环

代码语言:javascript
复制
function animate() {
  raf = window.requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  hexagonArray.forEach((hexagon) => {
    hexagon.toggle();
  });
}

代码语言:javascript
复制
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext("2d");
const hexagonArray = [];

let raf;

const items = [
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
  {
    heading: "Lorem Ipsum",
    subheading: "dolor sit amet",
  },
];

class Hexagon {
  constructor(heading, subheading, idx) {
    this.idx = idx;
    this.sixtyDeg = Math.PI * 2 / 6;
    this.radius = 80;
    this.gap = 1.9;
    this.fromX = canvas.width / 2;
    this.fromY = canvas.height / 2;
    this.toX = this.fromX + this.gap * this.radius * Math.sin(this.sixtyDeg * idx);
    this.toY = this.fromY + this.gap * this.radius * Math.cos(this.sixtyDeg * idx);
    this.x = this.fromX;
    this.y = this.fromY;
    this.frames = 100;
    this.frame = 0;
    this.speedX = this.toX / this.frames;
    this.speedY = this.toY / this.frames;
    this.isCurrent = false;
    this.heading = heading;
    this.subheading = subheading;
  }

  draw() {
    const { sixtyDeg, radius, x, y, idx } = this;
    // ctx.fillStyle = "red";
    // ctx.fillText(`no.${idx}`, x, y);
    ctx.beginPath();
    for (let i = 0; i < 6; i++) {
      ctx.lineTo(
        x + radius * Math.cos(sixtyDeg * i),
        y + radius * Math.sin(sixtyDeg * i)
      );
    }
    ctx.closePath();
    ctx.fill();
  }

  update(shouldOpen) {
    this.x = expEaseInOut(
      this.frame,
      this.fromX,
      this.toX - this.fromX,
      this.frames  
    );

    this.y = expEaseInOut(
      this.frame,
      this.fromY,
      this.toY - this.fromY,
      this.frames  
    );

    if (
      (shouldOpen ? this.frame < this.frames : this.frame > this.frames)
      && this.idx !== 0
    ) {
      this.frame = shouldOpen
        ? this.frame + 1  // open
        : this.frame - 1; // close
    } else if (this.idx !== 0) {
      stop();
    }

    this.draw();
  }

  toggle() {
    let toggle = false;
    this.update(!toggle);
    toggle = !toggle;
  }
}

function animate() {
  raf = window.requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  hexagonArray.forEach((hexagon) => {
    hexagon.toggle();
  });
}

function stop() {
  console.log('stop');
  window.cancelAnimationFrame(raf);
}

canvas.addEventListener('click', function (event) {
  const {
    clientX,
    clientY
  } = event;

  hexagonArray.some((hexagon) => {
    const isInRange = (
      inRange(clientX, hexagon.x - hexagon.radius, hexagon.x + hexagon.radius)
      && inRange(clientY, hexagon.y - hexagon.radius, hexagon.y + hexagon.radius)
    );
    if (isInRange) {
      raf = window.requestAnimationFrame(animate);
      return true;
    }
  });
});

function init() {
  items.forEach(({ heading, subheading }, idx) => {
    hexagonArray.push(new Hexagon(heading, subheading, idx));
  });
  hexagonArray.forEach((hexagon) => {
    hexagon.draw();
  });
}

init();

/** -------------------------------------------------------------------------------- */
/** -------------------------------------------------------------------------------- */
/** -------------------------------------------------------------------------------- */

window.addEventListener('resize', function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  init();
});

function expEaseInOut(frame, initPos, distance, frames) {
  frame /= frames / 2;
  if (frame < 1) return distance/2 * Math.pow( 2, 10 * (frame - 1) ) + initPos;
  frame--;
  return distance/2 * ( -Math.pow( 2, -10 * frame) + 2 ) + initPos;
};

function inRange(n, min, max) {
  return ((n-min)*(n-max) <= 0);
}
代码语言:javascript
复制
body {
  min-width: 100vw;
  min-height: 100vh;
  background-color: lightgray;
}

canvas {
  background-color: gray;
}
代码语言:javascript
复制
<canvas width="440" height="440"></canvas>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68613659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档