1 回答
TA贡献1843条经验 获得超7个赞
这是一种基本(简单)的方法,可以按照您想要的方向实现某些目标。
const asciiArt = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################.
......................`.split("\n");
const colorMap = {
"." : "black",
"#" : "white"
}
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
for (let y=0; y<asciiArt.length; y++) {
for (let x=0; x<asciiArt[y].length; x++) {
let sizeX = canvas.width / asciiArt[y].length,
sizeY = canvas.height / asciiArt.length;
let pixelX = sizeX * x,
pixelY = sizeY * y;
ctx.fillStyle = colorMap[asciiArt[y][x]] || "white";
ctx.fillRect(pixelX, pixelY, 30, 30);
}
}
<canvas id="canvas"></canvas>
一些解释:
我们在新行字符处拆分 asciiArt 使用.split("\n")
const asciiArt = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################.
......................`.split("\n");
现在我们遍历矩阵的y和x方向
for (let y=0; y<asciiArt.length; y++) {
for (let x=0; x<asciiArt[y].length; x++) {
// ...
}
}
在内部 for 循环中,我们在正确的位置用正确的颜色绘制矩形
colorMap[asciiArt[y][x]]
// This is the desired color ('.' --> "black", '#' --> "white")
添加回答
举报