3

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

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

11 Comments

One of the arrays in my example was empty - sorry for the typo! (The empty array should be [200, 200, 200]).
To change the array scale (in this example), you only need to change the pixel value in the css section. :)
@AndersonGreen: I just realized you can better use (0, 0, w, h) instead of the hardcoded (0, 0, 3, 3) for the arguments of getImageData.
It's also possible to resize the canvas so that it matches the dimensions of the array: stackoverflow.com/a/331462/975097
Here's my first attempt at getting the array to resize automatically. I'm still not sure whether it's working correctly. jsfiddle.net/zjypd/4
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.