var icon1 = new Image();
icon1.src = resource;
var width = icon1.width;
var height = icon1.height;
迭代时,此代码在第一次迭代时给出 0 作为宽度和高度,第二次给出正确的尺寸。
var icon1 = new Image();
icon1.src = resource;
var width = icon1.width;
var height = icon1.height;
迭代时,此代码在第一次迭代时给出 0 作为宽度和高度,第二次给出正确的尺寸。
您没有真正显示足够的代码(和一般上下文)来确定,但我敢打赌,第一次,图像还没有加载,第二次,它已经加载了。
您可以确保图像首先通过onload
事件加载。
var resource = "http://placehold.it/50";
var icon1 = new Image();
var wid1;
var hei1;
icon1.onload = function() {
wid1 = icon1.width;
hei1 = icon1.height;
console.log(wid1);
console.log(hei1);
};
icon1.src = resource;
在定义 onload 函数之前尝试将资源分配给 src。
var resource = "http://placehold.it/50";
var icon1 = new Image();
var wid1;
var hei1;
icon1.src = resource;
icon1.onload = function() {
wid1 = icon1.width;
hei1 = icon1.height;
console.log(wid1);
console.log(hei1);
};