开发者

putImageData doesn't 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.pu开发者_如何学PythontImageData(img, 0, 0);
}`

It doesn't seem to work on Chrome 8, since I am getting this image as a result:

putImageData doesn't show image

I've checked the img.data array produced by this function and the data are correct. So I assume that the problem is with the putImageData function. Has anyone else encountered the same problem? What could be wrong?


The canvas imagedata array is not 3 entries per a pixel [r,g,b] but 4 [r,g,b,a] , so if the %3 is supposed to be setting the alpha value, it should really be %4.

At the moment, theres an exception for the first entry (0), then it sets the 4th entry (i=3) to 255 (correct), but next it sets the 7th entry (i=6) to 255, which means rather than [r,g,b,a,r,g,b,a] you have [r,g,b,a,r,g,a,b], and it gets worse 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);
}`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜