Ed *_*nch 0 html javascript arrays image html5-canvas
所以我有一个像这样创建的二维数组:
//Fill screen as blank
for(var x = 0; x<500; x++ ){
screen[x] = [];
for(var y = 0; y<500; y++ ){
screen[x][y] = '#ffffff';
}
}
Run Code Online (Sandbox Code Playgroud)
并且想知道是否有一种简单的方法可以将其转换为 ImageData 对象,以便我可以在画布上显示它?
您必须学习的第一件事是如何展平二维数组。您可以使用嵌套循环并推送到新的一维数组,但我更喜欢使用reduceand concat:
const concat = (xs, ys) => xs.concat(ys);
console.log(
[[1,2,3],[4,5,6]].reduce(concat)
)Run Code Online (Sandbox Code Playgroud)
现在你会很快注意到你的矩阵将被翻转。ImageData逐行连接,但您的矩阵按列分组(即[x][y]代替[y][x])。我的建议是翻转你的嵌套循环:)
"#ffffff"到[255, 255, 255, 255]现在,您可以创建的十六进制代码(一维数组的工具screen.reduce(concat)),但ImageData需要一个Uint8ClampedArray的0-255值!让我们解决这个问题:
const hexToRGBA = hexStr => [
parseInt(hexStr.substr(1, 2), 16),
parseInt(hexStr.substr(3, 2), 16),
parseInt(hexStr.substr(5, 2), 16),
255
];
console.log(
hexToRGBA("#ffffff")
);Run Code Online (Sandbox Code Playgroud)
请注意,我跳过了第一个"#"字符并将 alpha 值硬编码为255.
我们将使用map一次转换新创建的一维数组:
screen.reduce(concat).map(hexToRGBA);
Run Code Online (Sandbox Code Playgroud)
回到第一个……我们再次被数组数组困住:
[ [255, 255, 255, 255], [255, 255, 255, 255], /* ... */ ]
Run Code Online (Sandbox Code Playgroud)
但是等等......我们已经知道如何解决这个问题:
const flattenedRGBAValues = screen
.reduce(concat) // 1d list of hex codes
.map(hexToRGBA) // 1d list of [R, G, B, A] byte arrays
.reduce(concat); // 1d list of bytes
Run Code Online (Sandbox Code Playgroud)
这是评论中链接到的部分,但我会将其包含在内,以便您可以有一个有效的示例!
screen.reduce(concat).map(hexToRGBA);
Run Code Online (Sandbox Code Playgroud)
[ [255, 255, 255, 255], [255, 255, 255, 255], /* ... */ ]
Run Code Online (Sandbox Code Playgroud)