javascript fetch image vs onload code example
Example 1: javascript load image programmatically
var elements = [];
function loaded(){
console.log("you have loaded an image");
}
CreateFileFrom("your/dir/here/img.png");
function CreateFileFrom(dir){
var extension = dir.split('.').pop();
var keys = {"png":"IMG","jpg":"IMG","jpeg":"IMG",
"js":"SCRIPT","json":"SCRIPT",
"mp3":"AUDIO","wav":"AUDIO"};
var obj = document.createElement(keys[extension]) || {};
obj.src = dir;
obj.onload = (e) => {
elements.push(e.path[0]);
loaded()
}
if(keys[extension]==null){console.error("not supported media type "+extension);return;}
}
Example 2: load images js context
function loadImage(url) {
return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
}
let img = await loadImage("./my/image/path.jpg");
ctx.drawImage(img, 0, 0);