微信小程序canvas怎么画出下面这样的动画效果?

小球上下移动的过程中,有一条轨迹线不断往左移动

阅读 3.2k
2 个回答

小球上下运动 跟着它划线就好了

https://codesandbox.io/s/smoo...

代码不多解释了,一看就懂。

const screenSize = [300, 300];
const canvas = document.createElement("canvas");
[canvas.width, canvas.height] = screenSize;
canvas.style.border = "1px solid black";
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");

class Vec2 {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
  add(other) {
    this.x += other.x;
    this.y += other.y;
  }
}

const shape = {
  pos: new Vec2(screenSize[0] / 2, screenSize[1] / 2),
  velocity: new Vec2(1, 1),
  radius: 10
};
const lines = [new Vec2(shape.pos.x, shape.pos.y)];

function loop() {
  update();
  render();
  requestAnimationFrame(loop);
}

function update() {
  // apply velocity
  shape.pos.add(shape.velocity);

  // collide with top and bottom
  const halfDownSize = 30;
  if (
    shape.pos.y >= screenSize[1] / 2 + halfDownSize ||
    shape.pos.y <= screenSize[1] / 2 - halfDownSize
  ) {
    lines.push(new Vec2(shape.pos.x, shape.pos.y));
    shape.velocity.y = -shape.velocity.y;
  }
}

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.save();

  //set camera follow the circle
  ctx.translate(screenSize[0] / 2 - shape.pos.x, 0);

  // draw circle
  ctx.beginPath();
  ctx.arc(shape.pos.x, shape.pos.y, shape.radius, 0, Math.PI * 2);
  ctx.fill();

  // draw lines
  const drawLine = (p0, p1) => {
    ctx.beginPath();
    ctx.moveTo(p0.x, p0.y);
    ctx.lineTo(p1.x, p1.y);
    ctx.stroke();
  };
  drawLine(lines[lines.length - 1], shape.pos);
  for (let i = 0; i < lines.length - 1; i++) {
    drawLine(lines[i], lines[i + 1]);
  }

  ctx.restore();
}

requestAnimationFrame(loop);

你是不是使用ctx.moveTo了?这个会绘制路径。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题