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

如何为HTML5 Canvas中的每个方块设置不同随机颜色?

解决Canvas方块各自拥有随机颜色的问题

嘿,问题很清晰啦——你现在只在代码最开始生成了一组随机RGB值,所有方块都复用这组值,自然颜色一模一样。咱们只需要把生成随机颜色的逻辑封装成一个函数,每次画方块前都调用它,就能让每个方块拥有独立的随机颜色了!

第一步:封装随机颜色生成函数

把你原来的随机数生成逻辑放进一个函数里,每次调用它都会返回一个全新的RGB颜色字符串:

function getRandomColor() {
  const red = Math.floor(Math.random() * 256); // 改成256能覆盖0-255的完整颜色范围
  const green = Math.floor(Math.random() * 256);
  const blue = Math.floor(Math.random() * 256);
  return `rgb(${red}, ${green}, ${blue})`;
}

小提示:原来的255改成256是因为Math.random()返回0到1(不包含1),这样Math.random()*256能取到0-255的所有整数,颜色选择更完整。

第二步:修改绘制逻辑,每个方块调用一次函数

每次绘制方块前,都调用getRandomColor()来设置新的fillStyle,修改后的完整代码如下:

<html>
  <canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>
  <script>
    var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");

    // 封装随机颜色函数
    function getRandomColor() {
      const red = Math.floor(Math.random() * 256);
      const green = Math.floor(Math.random() * 256);
      const blue = Math.floor(Math.random() * 256);
      return `rgb(${red}, ${green}, ${blue})`;
    }

    // 绘制第一个方块
    ctx.beginPath();
    ctx.rect(70, 50, 100, 100);
    ctx.fillStyle = getRandomColor(); // 每次都获取新颜色
    ctx.fill();

    // 绘制第二个方块
    ctx.beginPath();
    ctx.rect(220, 50, 100, 100);
    ctx.fillStyle = getRandomColor();
    ctx.fill();

    // 剩下的方块同理,每个都调用getRandomColor()
    ctx.beginPath();
    ctx.rect(370, 50, 100, 100);
    ctx.fillStyle = getRandomColor();
    ctx.fill();

    ctx.beginPath();
    ctx.rect(520, 50, 100, 100);
    ctx.fillStyle = getRandomColor();
    ctx.fill();

    ctx.beginPath();
    ctx.rect(670, 50, 100, 100);
    ctx.fillStyle = getRandomColor();
    ctx.fill();

    ctx.beginPath();
    ctx.rect(820, 50, 100, 100);
    ctx.fillStyle = getRandomColor();
    ctx.fill();
  </script>
</html>

进阶优化:用循环减少重复代码

你会发现现在的绘制代码重复度很高,咱们可以把所有方块的坐标放进数组,用循环批量绘制,以后要加新方块只需要往数组里加坐标就行:

<html>
  <canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>
  <script>
    var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");

    function getRandomColor() {
      const red = Math.floor(Math.random() * 256);
      const green = Math.floor(Math.random() * 256);
      const blue = Math.floor(Math.random() * 256);
      return `rgb(${red}, ${green}, ${blue})`;
    }

    // 存储所有方块的x坐标(y、宽、高都一样,所以只存x)
    const squareXPositions = [70, 220, 370, 520, 670, 820];
    
    squareXPositions.forEach(x => {
      ctx.beginPath();
      ctx.rect(x, 50, 100, 100);
      ctx.fillStyle = getRandomColor();
      ctx.fill();
    });
  </script>
</html>

这样代码更简洁,维护起来也更方便!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:48:02