i am doing something in which i create an html img element in javascript then i want that img width and height but when i try console log img width and height its return 0 but when i console log img whole object its showing proper value like this
let img = document.createElement("img")
img.src = "./img/img1.png"
console.log(img)
console.log(img.width)
console.log(img.height)
Here first console shows an html element which have both height and width with a different value like width is 580 and height is 100 but in second and third it shows 0 for width and for height too.
However, there is another thing when i try to run this script in with html file in script tag it run perfectly fine just like i wanted.
addition detail : my html file is normal html boiler plat and i am using script type 'text/javascript'
CodePudding user response:
width/height wont be known until the image has loaded, so you should use the onload
event if you want width/height
let img = document.createElement("img")
img.onload = () => {
console.log('works %sx%s', img.width, img.height)
}
img.src = "https://picsum.photos/200/300"
console.log('wont work %sx%s', img.width, img.height)
CodePudding user response:
you can use naturalHeight and naturalWidth instead of height and width it is working perfectly for me hope it is works for you also after pageload
let img = document.createElement("img");
img.src = "https://img.freepik.com/free-vector/colourful-illustration-programmer-working_23-2148281410.jpg?w=740&t=st=1649947934~exp=1649948534~hmac=1c14d627b3208ef3367c0cad486f2a20b72cacec394f8371a79b1a2aeb07ad45";
window.onload = function exampleFunction() {
console.log(img);
console.log(img.naturalHeight);
console.log(img.naturalWidth);
console.log("it is a freepik dummy image for testing");
// Function to be executed
}