gpt4 book ai didi

javascript - 如何获取Canvas图像数据?

转载 作者:行者123 更新时间:2023-12-03 05:08:26 24 4
gpt4 key购买 nike

我正在尝试读取图像数据,但每次都给我空白数组。

我在加载图像黑白时所做的事情,当我检查控制台日志中的数组输出时,它总是空白

// function to convert rgb to hex
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
// load image to canvas
function Load_mg(can_id,mg_src) {
var ctx = document.getElementById(can_id);
if (ctx.getContext) {
ctx = ctx.getContext('2d');
var img1 = new Image();
img1.onload = function () {
ctx.drawImage(img1, 0, 0);
};
img1.src = mg_src;
}
var can_ida = document.getElementById(can_id);
//var imgData = ctx.getImageData(0,0,can_ida.width,can_ida.height);
var imgData = ctx.getImageData(10, 10, 50, 50);
var data = imgData.data;

for(var i=0; i<data.length; i+=4) {
var red = data[i];
var green = data[i+1];
var blue = data[i+2];
var alpha = data[i+3];
if(red != 0){
console.log('some color found');
break;
}
var hex = "#" + ("000000" + rgbToHex(red,green, blue)).slice(-6);
// console.log('can_data hex '+hex+' Alpha '+alpha);
//if(i === 1000)break;
}

console.log(data);

} // function end point
Load_mg('test1','box_1.png');

fiddle :Jsbin

在 fiddle 中我通过base64图像数据加载图像

最佳答案

要解决此问题,只需将获取像素代码移动到 onload 事件中即可。

// function to convert rgb to hex
function rgbToHex(r, g, b) {
return "#" + (r < 10 ? "0" : "") + r.toString(16) +
(g < 10 ? "0" : "") + g.toString(16) +
(b < 10 ? "0" : "") + b.toString(16);
}
// load image to canvas
function Load_mg(can_id, mg_src) {
var ctx = document.getElementById(can_id);
if (ctx.getContext) {
ctx = ctx.getContext('2d');
var img1 = new Image();
img1.onload = function () {
ctx.drawImage(this, 0, 0);
var can_ida = document.getElementById(can_id);
//var imgData = ctx.getImageData(0,0,can_ida.width,can_ida.height);
var imgData = ctx.getImageData(10, 10, 50, 50);
var data = imgData.data;

for (var i = 0; i < data.length; i += 4) {
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
var alpha = data[i + 3];
if (red != 0) {
console.log('some color found');
break;
}
var hex = rgbToHex(red, green, blue);
}
};
img1.src = mg_src;
}

}
Load_mg('test1', 'box_1.png');

关于javascript - 如何获取Canvas图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41929155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com