Anderson Green
Anderson Green

Reputation: 31810

Copy a 2-dimensional pixel array to a Javascript canvas

Using the Javascript canvas element, is it possible to copy a 2-dimensional array of RGB values to a 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>

Upvotes: 3

Views: 3921

Answers (1)

pimvdb
pimvdb

Reputation: 154838

You can use getImageData/putImageData. Just calculate the right index (it's RGBA values in one big array): http://jsfiddle.net/zjypd/ (the jsFiddle has an enlarged canvas to show the pixels).

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

Upvotes: 4

Related Questions