javascript - Javascript image width is 0 on load
问题描述
I have this code for loading several images:
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();
but when I try to access the images in the load() functions, it says the width and height are 0, for me indicating the images aren't finished loading, but they should be? I'm dumbfounded...
解决方案
The problem is this line:
image.onload = imageLoaded(image);
Because you have the parenthesis, Javascript calls the function immediately and expects it to return the result that will be passed to the onload
You need something like this:
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();
The bind
function sets the value of this
in the function to the argument. This way, it won't call the function, but create it.
推荐阅读
- python - 如何将 pandas 数据框重新排列到此特定配置中?
- performance - 使用 emr spark 的雪花性能
- c# - 当锁定持续时间未过去时,Azure 服务总线为非分区队列抛出 MessageLockLostException
- ios - 向阿拉伯语文本添加自动 kashida/跟踪(不是字距调整)
- c# - 从 Angular 前端提交后,API 控制器中的模型为空
- symfony - API 平台 GraphQL 关系中的安全性
- reactjs - react-beautiful-dnd 如何在 Droppable 之外设置拖动项目的样式
- javascript - 隐藏滤芯
- flutter - 强制颤振的 TabBarView 适应其内容
- c# - 在c#中制作数据透视表的行数限制