javascript - Render 1 pixel from a 3D array in a HTML5 Canvas using putImageData() and an UInt8ClampedArray
问题描述
I tried my best to render just 1 pixel form a 3D Array in a HTML5 Canvas unsuccessfully.
(I know this has been done before but not with a 3D Array). But converting a 3D array to an Uint8ClampedArray and pushing to an Uint8ClampedArray isn't easy.
HTML5 also doesn't have another way to display a pixel manipulatable image.
Is it correct that putImageData() is for rendering vertical strings of pixels?
Here is my code, the problem is marked with: "WHAT DO I GOTTA DO HERE":
<!DOCTYPE html>
<html lang="en" + dir="ltr">
<head>
<meta charset="UTF-8">
<title>
Index.html
</title>
</head>
<body style="margin: 0px; padding: 0px;">
<canvas id="canvas">
</canvas>
<script>
let a = new Array();
a.push([]);
a[x.length - 1].push([]);
a[x.length - 1][a[a.length - 1].length - 1].push(0);
a[x.length - 1][a[a.length - 1].length - 1].push(0);
a[x.length - 1][a[a.length - 1].length - 1].push(0);
a[x.length - 1][a[a.length - 1].length - 1].push(255);
document.getElementById("canvas").getContext("2d").putImageData(new
ImageData(new Uint8ClampedArray("WHAT DO I GOTTA DO HERE"), 1, 1), 1,
1);
</script>
</body>
</html>
To test it you can use:
console.log(a);
console.log(a[0]);
console.log(a[0][0]);
console.log(a[0][0][0]);
解决方案
在画布上绘制 200 x 200 的红色块。需要<canvas></canvas>
我建议不要使用 3D 数组,因为它看起来不必要地复杂
const width = 200;
const height = 200;
const canvas = document.getElementsByTagName('canvas')[0];
const context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
const destData = new ImageData(width, height);
const dData = destData.data;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = 4 * (y * width + x);
dData[o] = 255; // R
dData[o + 1] = 0; // G
dData[o + 2] = 0; // B
dData[o + 3] = 255; // A
}
}
context.putImageData(destData, 0, 0);
推荐阅读
- docker - coredns pod 具有 CrashLoopBackOff 或错误状态
- ios - iOS:如何在 Swift 中为视图创建顶部/底部圆角和阴影
- c# - WinForm 中的 C# 自定义控件,带有 DataGridView 和条形图
- python - 为不受信任的 python 代码创建安全环境
- c - 检查数组 3x3 是否都不是某个字符?
- javascript - 为什么 date.valueOf() == date 结果为假?
- javascript - 如何将可观察响应投射到本地对象
- css - 另一个 div 标签顶部的 CSS 重叠图像
- confluence - 将 Confluence 页面导出/访问为 HTML,包括图形
- wordpress - 如何在 wordpress 中创建页面别名