PutImageData does not show image

I use the following function to update the contents of a canvas element, where frame_data is an array of width*height*3 .

 function updateCanvas(frame_data, width, height) { img = ctx.createImageData(width, height); for (i=0, j=0; j < frame_data.length; i++) { if ((i > 0) && (i%3==0)) { img.data[i] = 255; } else { img.data[i] = frame_data[j++]; } } ctx.putImageData(img, 0, 0); }` 

It does not work in Chrome 8, since I get this image as a result:

enter image description here

I checked the img.data array created by this function and the data is correct. Therefore, I assume that the problem is with the putImageData function. Has anyone else encountered the same problem? What could be wrong?

+4
source share
1 answer

The imagedata canvas layout is not 3 records per pixel [r, g, b], but 4 [r, g, b, a], therefore, if it is assumed that% 3 sets the alpha value, it must really be% 4.

This is currently an exception for the first record (0), then it sets the fourth record (i = 3) to 255 (correct), but then sets the 7th record (i = 6) to 255, and instead of [r, g, b, a, r, g, b, a] you have [r, g, b, a, r, g, a, b] and worsens over time.

Try

 function updateCanvas(frame_data, width, height) { img = ctx.createImageData(width, height); for (i=0;j=0; j < frame_data.length; j=j+3) { img.data[i] = frame_data[j]; img.data[i+1] = frame_data[j+1]; img.data[i+2] = frame_data[j+2]; img.data[i+3] = 255; i+=4; } ctx.putImageData(img, 0, 0); }` 
+6
source

Source: https://habr.com/ru/post/1342562/


All Articles