You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Canvas动画循环?两种绘制样式持续交替切换

解决Canvas绘制样式持续交替切换问题

你的代码仅执行了一次draw,之后一直重复执行repaint,因此只能完成一次切换。要实现两种绘制样式的持续交替,需要引入状态标记来控制每次执行的绘制函数:

修改思路

  • 新增状态变量记录当前要执行的绘制模式
  • 用定时器每隔1秒切换状态,并触发对应绘制函数
  • 每次绘制前清除画布,避免之前的绘制残留干扰显示效果

修改后的代码

JavaScript部分

document.getElementById("square").style.backgroundColor = "red";
document.getElementById("square").style.border = "2px solid black";
const c = document.getElementById("square");
const ctx = c.getContext("2d");

// 状态标记:true执行draw,false执行repaint
let isDrawMode = true;

const repaint = () => {
  // 清除整个画布
  ctx.clearRect(0, 0, c.width, c.height);
  document.getElementById("square").style.backgroundColor = "white";
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, 200, 200);
  ctx.fillRect(400, 0, 200, 200);
  ctx.fillRect(200, 200, 200, 200);
  ctx.fillRect(600, 200, 200, 200);
};

const draw = () => {
  // 清除整个画布
  ctx.clearRect(0, 0, c.width, c.height);
  if (c.getContext) {
    ctx.beginPath();
    ctx.moveTo(0, 200);
    ctx.lineTo(800, 200);
    ctx.moveTo(400, 0);
    ctx.lineTo(400, 400);
    ctx.moveTo(200, 0);
    ctx.lineTo(200, 400);
    ctx.moveTo(600, 0);
    ctx.lineTo(600, 400);
    ctx.stroke();
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, 200, 200);
    ctx.fillRect(400, 0, 200, 200);
    ctx.fillRect(200, 200, 200, 200);
    ctx.fillRect(600, 200, 200, 200);
  }
};

// 初始化执行一次draw
draw();

// 每隔1秒切换模式并执行对应函数
setInterval(() => {
  isDrawMode = !isDrawMode;
  isDrawMode ? draw() : repaint();
}, 1000);

HTML部分(无需修改)

<!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">
  <title>Animated flag</title>
</head>

<body>
  <div>

  </div>
  <canvas id="square" width="800" height="400"></canvas>
  <script src="./red-white-animation.js"></script>
</body>

</html>

关键说明

  • 状态变量isDrawMode:通过布尔值切换当前要执行的绘制函数,每次定时器触发时取反状态。
  • ctx.clearRect():每次绘制前清除整个画布,避免之前的绘制内容残留,保证每次绘制都是全新的状态。
  • 定时器逻辑:用setInterval实现1秒间隔的状态切换,确保两种绘制样式循环交替执行。

内容的提问来源于stack exchange,提问作者fadingbeat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:35:19