Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of image in vueJs mounted

I need to get the height and the width of an image who is in the local asset folder of my project.

I try to do like in the mounted() :

let grid = new Image()
grid.src = require('../../assets/sprites/grid.png');
console.log(grid.naturalWidth, grid.naturalHeight)

But I always have 0 instead of 3030px

EDIT:

I found a half-solution because it's not complete this.gridPattern is defined in data above, I need to re-assign it value but , the value is 0

let grid = new Image()

grid.src = require('../../assets/sprites/grid_pathern.png');

grid.onload = () => {
    console.log(`the image dimensions are ${grid.width}x${grid.height}`);
    this.gridPattern = {width:grid.width,height:grid.height}
    console.log(this.gridPattern)
    };
like image 506
Seb Avatar asked Nov 18 '25 10:11

Seb


1 Answers

You will need to await the image to be fully loaded beforehand in order to get the width and height of an instantiated image.

async mounted() {
    let image = new Image();
    
    image.onload = function () {
        console.log(`the image dimensions are ${img.width}x${img.height}`);
    };
   
    image.src = require('../../assets/sprites/grid_pathern.png');
}
like image 181
PatricNox Avatar answered Nov 20 '25 23:11

PatricNox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!