将二维像素数组复制到Javascript画布

时间:2012-12-11 18:33:40

标签: javascript canvas

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

<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>

1 个答案:

答案 0 :(得分:3)

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

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);