canvas绘画格子

发布时间 2023-07-20 12:50:53作者: 小小菜鸟04
<!DOCTYPE html>
<html>
<head>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
  <script>
    let canvas;
    let ctx;
   
    // 自定义格子数据,包含内容和颜色
    const gridData = [
      { content: "这是第一行文本\n这是第二行文本", color: "#ff0000" },
      { content: "B", color: "#00ff00" },
      { content: "C", color: "#0000ff" },
      // 其他格子数据
    ];
   
    function init() {
      canvas = document.getElementById("canvas");
      ctx = canvas.getContext("2d");
      drawGrid();
    }
   
    function drawGrid() {
      const gridSize = Math.ceil(Math.sqrt(gridData.length)); // 根据数据长度计算格子数量
      const cellSize = Math.min(canvas.width / gridSize, canvas.height / gridSize); // 计算格子大小
     
 // canvas.width = cellSize * gridSize;
  //   canvas.height = cellSize * gridSize;
      ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
     
      for (let i = 0; i < gridData.length; i++) {
        const row = Math.floor(i / gridSize);
        const col = i % gridSize;
       
        const x = col * cellSize;
        const y = row * cellSize;
       
        const cellData = gridData[i];
       
        // 绘制格子背景颜色
        ctx.fillStyle = cellData.color;
        ctx.fillRect(x, y, cellSize, cellSize);
       
        // 绘制格子边框
        ctx.strokeStyle = "#000"; // 设置边框颜色为黑色
        ctx.lineWidth = 2; // 设置边框宽度为2像素
        ctx.strokeRect(x, y, cellSize, cellSize);
       
        // 绘制格子内容
        ctx.fillStyle = "white"; // 将字体颜色设置为白色
        ctx.font = "24px Arial"; // 设置字体样式
        ctx.textBaseline = "middle"; // 设置文本对齐方式
        ctx.textAlign = "center";
        ctx.fillText(cellData.content, x + cellSize / 2, y + cellSize / 2);
      }
    }
  </script>
</head>
<body onload="init()">
  <canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>