1 回答

TA貢獻1843條經(jīng)驗 獲得超7個贊
這是一種基本(簡單)的方法,可以按照您想要的方向?qū)崿F(xiàn)某些目標。
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");
現(xiàn)在我們遍歷矩陣的y和x方向
for (let y=0; y<asciiArt.length; y++) {
for (let x=0; x<asciiArt[y].length; x++) {
// ...
}
}
在內(nèi)部 for 循環(huán)中,我們在正確的位置用正確的顏色繪制矩形
colorMap[asciiArt[y][x]]
// This is the desired color ('.' --> "black", '#' --> "white")
添加回答
舉報