我试图获取图像的像素颜色有点困难。我需要获取一个像素的RGB值,跳三并将其存储在一个数组中,但我的控制台总是返回[0,0,0 ...]。
你知道如何以更好的方式做到这一点吗?
我的代码如下所示:
function captureImageData( image )
{
var cnv = document.createElement( 'canvas' );
cnv.width = image.width;
cnv.height = image.height;
var ctx = cnv.getContext( '2d' );
ctx.drawImage( image, 0, 0 );
var imageData = ctx.getImageData( 0, 0, 200, 100 );
var data = imageData.data;
var height = imageData.height;
var width = imageData.width;
for ( var y = 0; y < 100; y += 2 )
{
for ( var x = 0; x < 200; x += 2 )
{
red.push(data[( y * imageData.width + x ) * 4 + 0]);
green.push(data[( y * imageData.width + x ) * 4 + 1]);
blue.push(data[( y * imageData.width + x ) * 4 + 2]);
alpha.push(data[( y * imageData.width + x ) * 4 + 3]);
}
}
console.log( red );
}
答案 0 :(得分:0)
你是如何将图像传递给函数的?尝试以下,它对我来说很好。
<强> Live Demo 强>
var red = [],
green = [],
blue = [],
alpha = [];
function captureImageData(image) {
var cnv = document.createElement('canvas');
cnv.width = image.width;
cnv.height = image.height;
var ctx = cnv.getContext('2d');
ctx.drawImage(image, 0, 0);
var imageData = ctx.getImageData(0, 0, 200, 100);
var data = imageData.data;
var height = imageData.height;
var width = imageData.width;
var index = 0;
for (var y = 0; y < 100; y += 2) {
for (var x = 0; x < 200; x += 2) {
index = (y * imageData.width + x) * 4;
red.push(data[index]);
green.push(data[index + 1]);
blue.push(data[index + 2]);
alpha.push(data[index + 3]);
}
}
// log out any pixel here
console.log(red[1]);
}
var image = new Image();
image.crossOrigin = true;
image.src = "http://i.imgur.com/LdmrhlK.jpg";
image.onload = function () {
captureImageData(this);
}