gpt4 book ai didi

javascript - 回调返回真/假

转载 作者:行者123 更新时间:2023-12-03 02:57:19 26 4
gpt4 key购买 nike

我想知道我在这里缺少什么我有一个代码可以检查图像是否基于 Canvas 是透明的。

function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}

当我这样做时:

        function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}

function callback(success, npc) {
if (success) {
console.log("Not trasparent");
} else {
console.log("Trasparent");
}
}


Trasparent(npc.icon, npc, callback);

它工作得很好,但是当我尝试像这样创建上面的函数时:

function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
return false;
} else {
return true;
}
};
}


if(Transparent(npc.icon, npc)){
console.log("Not transparent");
} else {
console.log("Trasparent");
}

这不起作用...

即使在我编写的这个示例中,它也可以正常工作:

function check(a, b) {
var result = a + b;
if (result <= 10) {
return (false);
} else {
return (true);
}
}


function test() {
if (check(5, 4)) {
console.log(">10");
} else {
console.log("<10")
}
}
test();

我缺少什么?

最佳答案

返回语句不属于函数Transparent!

您正在此处创建一个不同的函数,该函数在调用时返回 true 或 false,但它不会立即执行,并且它的返回值不会在您的函数 Transparent 中返回。您所拥有的基本上是这个片段:

function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = function() {
// function body totally unrelated to the Transparent-function
// and not executed and not returning anything right now
};
return undefined;
}

(这些实际上并不相同,因为胖箭头函数捕获 this,请参阅 What does "this" refer to in arrow functions in ES6? )

使用回调的解决方案是正确的选择。

关于javascript - 回调返回真/假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47567066/

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