canvas绘制圆制作吃豆豆,结果在计时器中加入clearRect也毫无作用,无法清除上一次绘制的动画

canvas 简单绘制吃豆豆按理来说应该是这样的

可结果是这样的,不是你想象的样子

即使是在绘制之前添加了clearRect也不行,最终发现要在每个绘制之前加入ctx.beginPath();就可以了

以下为最终代码

html与scc部分

 <style>
    canvas {
        width: 500px;
        height: 300px;
        border: 1px solid;
    }
</style>
<canvas id="canvas" width="500" height="300"></canvas>

js部分

  const canvas = document.getElementById("canvas");
  const ctx = canvas.getContext("2d");
  /**
  * 画圆 弧度(Π)与角度关系 360°=2*Math.PI 90°=Math.PI/2 顺时针
  * 圆心(x,y) 半径r,弧度(起始弧度,结束弧度),方向(false:顺时针,true:逆时针);
  * arc(x,y,r,起始弧度,结束弧度,false)
  *  ctx.arc(100,100,50,0,Math.PI*angle,false);
     */
  let angle = 1.7, //嘴巴角度
  x1 = 50, //嘴巴的初始位置
  x2 = 110, //球的初始位置
  eyes = 40, //眼睛的初始位置
  timer = null;
  // 张嘴
  timer = setInterval(() => {
      ctx.clearRect(0, 0, 500, 300);
      drawMouth();
      drawBall();
  }, 10000 / 60)

  function drawMouth() {
      if (angle === 1.8) {
          angle = 1.7;
          eyes -= 10;
      } else {
          eyes += 10;
          angle = 1.8
      }
      //绘制嘴巴
      ctx.beginPath();
      ctx.arc(x1, 100, 50, 0, Math.PI * angle, false);
      ctx.lineTo(x1, 100);
      ctx.closePath();
      ctx.stroke();
      // 绘制眼睛
      ctx.beginPath();
      ctx.arc(eyes, 70, 8, 0, Math.PI * 2, false);
      ctx.fill();
      ctx.stroke();
      eyes++;
      x1++;
  }

  function drawBall() {
      if (angle === 1.8) {
          x2 -= 10;
      } else {
          x2 += 10
      }
      //当球的位置到达了画布的最左边就停止
      if (x2 >= (500 - 10)) {
          clearInterval(timer)
          return;
      }
      //绘制球
      ctx.beginPath();
      ctx.arc(x2, 84, 10, 0, Math.PI * 2, false);
      ctx.fill();//颜色填充
      ctx.stroke();
      x2++;
  }

遇到的问题:

在没有加入 ctx.beginPath();虽然你加了ctx.clearRect(0, 0, 500, 300);

但是想要清除画布你会发现根本清除不了;

如果不加上它会认为你是在同时绘制,是没有结束所以就会一直绘制下去,

所有想要达到效果就得在每个绘制之前加上ctx.beginPath();

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值