Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript从图像区域获取RGB数据_Javascript_Html_Image_Canvas_Rgb - Fatal编程技术网

如何使用JavaScript从图像区域获取RGB数据

如何使用JavaScript从图像区域获取RGB数据,javascript,html,image,canvas,rgb,Javascript,Html,Image,Canvas,Rgb,我无法从图像中获取RGB数据,我要做的是获取某个区域的de x,y,宽度和高度,因此,我想知道该区域的RGB数据,而不是该区域的像素 我试着使用一个带有getImageData的画布,但它只返回一个像素,我使用一个库来获取x、y、w和h的参数,我的图像大小与画布相同 这就是我所做的 const canvas2 = document.getElementById('canvasIMG'); //Get the canvas const img2 = document.getElementById(

我无法从图像中获取RGB数据,我要做的是获取某个区域的de x,y,宽度和高度,因此,我想知道该区域的RGB数据,而不是该区域的像素

我试着使用一个带有getImageData的画布,但它只返回一个像素,我使用一个库来获取x、y、w和h的参数,我的图像大小与画布相同

这就是我所做的

const canvas2 = document.getElementById('canvasIMG'); //Get the canvas
const img2 = document.getElementById('imagen');//Get the image
const ctxImagen = canvas2.getContext('2d');//Get the context of canvas
ctxImagen.drawImage(img, 0, 0);
var rgb = ctxImagen.getImageData(ejex,ejey,1000, 1000).data; //"ejex" is the x coordinate and "ejey" is y coordinate, and 1000 is the width and the height, i tried to change the values of w and h, and is the same always, I download a RGB image, and in the console just print the color of both uppset corners
console.log("red ", rgb[0]);
console.log("green ", rgb[1]);
console.log("blue ", rgb[2]);
console.log("alpha ", rgb[3]);

我没有收到任何错误消息。

要获得一个区域像素的平均值,你应该先得到该区域,然后自己计算平均值(我在这里做了一个渐变,因为我实际上无法在堆栈溢出时将图像导入画布,因为这将是一个CORS问题):

const canvas=document.createElement('canvas');
const ctx=canvas.getContext('2d');
常数梯度=ctx.createLinearGradient(0,0,500,500);
渐变。添加颜色停止(0,'红色');
渐变。添加颜色停止(1,'蓝色');
document.body.appendChild(画布);
canvas.width=canvas.height=500;
ctx.fillStyle=渐变;
ctx.fillRect(0,0500500);
const data=ctx.getImageData(0,0500500).data;
常量平均值={r:0,g:0,b:0,a:0};//创建一个对象以向上计数所有值
常量像素=data.length/4;//实际读取的像素数
//现在让我们在所有像素之间循环。它们是[r,g,b,a]值的平面数组,从左上到右下依次排列。所以每四个条目形成一个像素。
对于(设i=0;ictx.strokeRect(20,20,50,50)你必须循环遍历图像数据,并对每个分量求和,然后除以像素数得到平均值。你能再解释一下吗?请