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

如何进一步重构基于行列的ctx.fillStyle代码?

Optimizing Row/Column-Based FillStyle Assignment

Your current code is full of repetitive conditional checks and redundant variables, which makes it hard to maintain and read. A far cleaner approach is to use a 2D color matrix that directly maps column and row indices to their corresponding fill colors. Here's how to refactor it:

Step 1: Define Your Color Matrix

First, create a 2D array where each outer array represents a column, and each inner element corresponds to the color for that row in the column. This mirrors your original logic but organizes it in a way that’s easy to scan and update:

// Map [column][row] to fill color (match your original values here)
const colorMatrix = [
  // Column 0: rows 0 through 5
  ["#9fc30d", "#d13d42", "#1bf839", "#6776ef", "#d13e9e", "#339ca6"],
  // Column 1: rows 0 through 5 (fill in the remaining colors you had here)
  ["#43f7ac", "...", "...", "...", "...", "..."]
];

Step 2: Simplify the Style Assignment

Replace all those nested if statements and row-check variables with a single lookup. We’ll add a quick bounds check to avoid errors if c or r fall outside your expected ranges:

// Check if column and row are within valid bounds to prevent index errors
if (c >= 0 && c < colorMatrix.length && r >= 0 && r < colorMatrix[c].length) {
  ctx.fillStyle = colorMatrix[c][r];
}

Why This Works Better

  • Readability: Anyone looking at the code can immediately visualize the color layout for each column and row.
  • Maintainability: Adding a new column or row just means updating the colorMatrix—no need to write dozens of new if statements.
  • Reduced Redundancy: Eliminates all those unnecessary r0/r1 variables and nested conditionals cluttering up your code.
  • Scalability: If you ever need to expand to more columns or rows, this approach scales seamlessly without rewriting core logic.

If you have edge cases (like cells that don’t need a color assignment), you can add a fallback with optional chaining for safety:

// Use a default color if the cell has no defined value
ctx.fillStyle = colorMatrix[c]?.[r] || "#your-default-color";

内容的提问来源于stack exchange,提问作者E. Choi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:08:37