如何进一步重构基于行列的ctx.fillStyle代码?
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 newifstatements. - Reduced Redundancy: Eliminates all those unnecessary
r0/r1variables 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

