Javascript 加载时图像宽度为 0
Javascript image width is 0 on load
我有这段代码可以加载多张图片:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(i){
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded(image);
}
}
onload = loadAssets();
但是当我尝试访问 load() 函数中的图像时,它说宽度和高度为 0,对我来说表明图像没有完成加载,但它们应该是?我傻眼了...
问题出在这一行:
image.onload = imageLoaded(image);
因为你有括号,Javascript 立即调用该函数并期望它 return 将传递给 onload
的结果
你需要这样的东西:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(){
var i = this
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded.bind(image);
}
}
onload = loadAssets();
bind
函数将函数中this
的值设置为参数。这样,它不会调用该函数,而是创建它。
我有这段代码可以加载多张图片:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(i){
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded(image);
}
}
onload = loadAssets();
但是当我尝试访问 load() 函数中的图像时,它说宽度和高度为 0,对我来说表明图像没有完成加载,但它们应该是?我傻眼了...
问题出在这一行:
image.onload = imageLoaded(image);
因为你有括号,Javascript 立即调用该函数并期望它 return 将传递给 onload
的结果
你需要这样的东西:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(){
var i = this
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded.bind(image);
}
}
onload = loadAssets();
bind
函数将函数中this
的值设置为参数。这样,它不会调用该函数,而是创建它。