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

实现HTML5 Canvas方块点击后红绿色无限循环切换的方案

HTML5 Canvas方块点击切换红绿循环实现方案

现有4个初始填充为红色的HTML5 Canvas方块,需求为点击任意方块时切换为绿色,再次点击切回红色,形成无限循环。以下是可行的实现方案,基于你提供的代码改造:

<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>

<canvas id="myCanvas" onclick="toggleColor(event)" width="300" height="150" style="border:1px solid grey"></canvas>
<canvas id="myCanvas2" onclick="toggleColor(event)" width="300" height="150" style="border:1px solid grey"></canvas>
<canvas id="myCanvas3" onclick="toggleColor(event)" width="300" height="150" style="border:1px solid grey"></canvas>
<canvas id="myCanvas4" onclick="toggleColor(event)" width="300" height="150" style="border:1px solid grey"></canvas>

<script>
// 统一初始化所有Canvas为红色
const canvases = document.querySelectorAll('canvas');
canvases.forEach(canvas => {
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'red';
    ctx.fillRect(50, 50, 150, 100);
    // 用dataset存储当前颜色状态
    canvas.dataset.currentColor = 'red';
});

function toggleColor(event) {
    const canvas = event.target;
    const ctx = canvas.getContext('2d');
    const currentColor = canvas.dataset.currentColor;
    
    // 切换颜色
    const newColor = currentColor === 'red' ? 'green' : 'red';
    ctx.fillStyle = newColor;
    ctx.fillRect(50, 50, 150, 100);
    // 更新状态
    canvas.dataset.currentColor = newColor;
}
</script>
</body>
</html>

关键实现说明

  • 通用点击处理:通过event.target获取当前点击的Canvas元素,无需为每个Canvas单独编写函数,实现逻辑复用
  • 状态存储:利用Canvas元素的dataset属性存储当前颜色状态,避免依赖Canvas上下文的fillStyle(该属性可能因其他绘制操作被意外修改)
  • 统一初始化:通过querySelectorAll批量获取所有Canvas,循环完成红色方块的初始化,减少重复代码,提升可维护性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:23:18