gpt4 book ai didi

javascript - 在 JavaScript 函数中加载图像

转载 作者:行者123 更新时间:2023-11-30 07:37:29 25 4
gpt4 key购买 nike

我有获取图像像素颜色的函数

function getImage(imgsrc){
var img = $( "<img>", {
src: imgsrc
});
var imageMap = new Object();
img.load(function() {
var canvas = $('<canvas/>')[0].getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvas.drawImage(this, 0, 0, this.width, this.height);
for(var i = 0;i < this.width;i++){
imageMap[i] = new Object();
for(var j = 0;j < this.width;j++){
var pixelData = canvas.getImageData(i, j, 1, 1).data;
imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
}
}
console.log(imageMap[40][40]);
});
console.log(imageMap[40][40]);
return imageMap;
}

但它返回未定义(它首先打印第二个 console.log)怎么了?

谢谢。

最佳答案

您的函数返回 undefined 因为 load 是异步的。 getImage 试图在 load 完成加载之前返回一些内容。

您需要将回调传递给 getImage,以便在图像加载后执行:

function getImage(imgsrc, callback){
var img = $( "<img>", {
src: imgsrc
});
var imageMap = new Object();
img.load(function() {
var canvas = $('<canvas/>')[0].getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvas.drawImage(this, 0, 0, this.width, this.height);
for(var i = 0;i < this.width;i++){
imageMap[i] = new Object();
for(var j = 0;j < this.width;j++){
var pixelData = canvas.getImageData(i, j, 1, 1).data;
imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
}
}
console.log(imageMap[40][40]);
callback(imageMap)
});
}

然后你只需像这样调用函数:

getImage("http://some.src.jpg", function(imageMap){
// Do stuff with imageMap here;
});

当然你也可以在别处定义回调:

var myCallback = function(imageMap){
// Do stuff with imageMap here;
};

getImage("http://some.src.jpg", myCallback);

关于javascript - 在 JavaScript 函数中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405879/

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