getImageData()返回全0 [英] getImageData() returning all 0's
问题描述
所以,我有一个像这样的函数:
So, I have a function like this:
var getRGBArray = function (img) {
// create the canvas we need to work with
var canvas = document.createElement('canvas');
// get the canvas context
var context = canvas.getContext("2d");
// will store the image data and the returned array
var imgData, rgbArray = [];
// make sure that the width and height are correct
context.canvas.width = img.naturalWidth;
context.canvas.height = img.naturalHeight;
// draw the image
context.drawImage(img, img.naturalWidth, img.naturalHeight);
// get the image data
imgData = context.getImageData(0, 0, img.naturalWidth, img.naturalHeight);
// imgData contains r,g,b,alpha values. We skip
// the alpha value.
for (var i = 0, n = 0; i < imgData.data.length; i+=4, n+=3) {
rgbArray[n] = imgData.data[i];
rgbArray[n+1] = imgData.data[i+1];
rgbArray[n+2] = imgData.data[i+2];
// imgData.data[i+3] is the alpha channel. We ignore it.
}
return rgbArray;
};
仅应拍摄图像并返回设置为[r0, g0, b0, r1, g1, b1, ..., rn, gn, bn]
的数组.
Which is just supposed to take an image and return an array that's set up like [r0, g0, b0, r1, g1, b1, ..., rn, gn, bn]
.
首先,返回的数组完全为空,这显然是一个问题.
First, the array that is returned is completely empty, which is obviously a problem.
第二,当我将所有这些内容输入Firefox的控制台窗口时,imgData
数组的长度是合理的,但是所有数据都是0!没有一个值是不确定的,并且我正在调试一个简单的网页.该网页已经加载了图片,而我只是使用document.getElementById('testImage')
来获取图片.
Second, when I input all of this stuff into the console window on Firefox, the imgData
array is a reasonable length, but all of the data is 0! None of the values are coming up undefined, and I have a simple webpage I'm debugging on. The webpage already has the image loaded, and I'm just getting the image using document.getElementById('testImage')
.
有人可以向我解释为什么会这样吗?
Can someone please explain to me why this is happening?
这不同于此因为我想知道drawImage()
为什么要给我返回全为0的数据数组.他们在问完全不同的事情.
This is different from this because I was wondering why drawImage()
was giving me back a data array with all 0's. They are asking completely different things.
推荐答案
我发现了问题.在context.drawImage()
中,我没有通过起始位置.解决方法是更改它,就像:context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight)
.谢谢您的帮助!
I found the issue. In context.drawImage()
I wasn't passing in the start position. The fix is to change it so it's like: context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight)
. Thank you for your help!
这篇关于getImageData()返回全0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!