Šajā piemērā jūs iemācīsities rakstīt JavaScript programmu, kas iegūs attēla izmērus.
Piemērs: Iegūstiet attēla izmērus
// program to get the dimensions of an image const img = new Image(); // get the image img.src = '//cdn.programiz.com/sites/tutorial2program/files/cover-artwork.png.webp'; // get height and width img.onload = function() ( console.log('width ' + this.width) console.log('height '+ this.height); )
Rezultāts
platums 1040 augstums 922
Iepriekš minētajā programmā new Image()
attēla objekta izveidošanai tiek izmantots konstruktors.
Image()
Konstruktors izveido jaunu attēla elementu instancē.
img.src
pēc tam tiek izmantots, lai pievienotu attēlu, izmantojot attēla URL avotu.
img.onload()
Funkcija tiek izmantota, lai piekļūtu augstumu un platumu attēla.