gpt4 book ai didi

javascript - 将二维像素数组复制到 Javascript Canvas

转载 作者:行者123 更新时间:2023-11-29 20:02:05 26 4
gpt4 key购买 nike

使用 Javascript Canvas 元素,是否可以将 RGB 值的二维数组复制到 Canvas ?

<html>
<body>
<canvas id="canvas" height="200" width="200"></canvas>
<script type = "text/javascript">

//copy the following array to the canvas:
var arr1 = [
[[255, 255, 255],[200, 200, 0],[200, 200, 200]],
[[200, 0, 0],[200, 200, 0],[200, 200, 0]],
[[200, 200, 0],[200, 0, 0],[200, 200, 0]]
]

<script>
</body>
</html>

最佳答案

您可以使用getImageData/putImageData。只需计算正确的索引(它是一个大数组中的 RGBA 值):http://jsfiddle.net/zjypd/ (jsFiddle 有一个放大的 Canvas 来显示像素)。

var arr1 = [
[[255, 255, 255],[200, 200, 0],[]],
[[200, 0, 0],[200, 200, 0],[200, 200, 0]],
[[200, 200, 0],[200, 0, 0],[200, 200, 0]]
];

var ctx = document.querySelector("canvas").getContext("2d");

var height = arr1.length;
var width = arr1[0].length;

var h = ctx.canvas.height;
var w = ctx.canvas.width;

var imgData = ctx.getImageData(0, 0, w, h);
var data = imgData.data; // the array of RGBA values

for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
var s = 4 * i * w + 4 * j; // calculate the index in the array
var x = arr1[i][j]; // the RGB values
data[s] = x[0];
data[s + 1] = x[1];
data[s + 2] = x[2];
data[s + 3] = 255; // fully opaque
}
}

ctx.putImageData(imgData, 0, 0);

关于javascript - 将二维像素数组复制到 Javascript Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13826319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com