获取安装的vueJs中图像的大小



我需要获取项目的本地资产文件夹中的图像的高度和宽度。

我试着在mounted((中做类似的事情:

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

但我总是有0而不是3030px

编辑:

我找到了一半的解决方案,因为它不完整gridPattern是在上面的数据中定义的,我需要重新分配它的值,但是,值是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)
};

您需要提前等待图像完全加载,才能获得实例化图像的宽度和高度。

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');
}

我的理解是,如果不将图像放在DOM中,就无法查询图像的高度和宽度,除非您已经通过编程为其分配了heightwidth。相反,您希望查询自然高度和宽度(naturalHeightnaturalWidth(,这是图像在放入DOM之前的原始维度。我还建议将您计划以程序方式调用的任何内容添加到data对象中。

import MyImage from '../../assets/sprites/grid.png';
export default {
[...],
data() {
return {
myImage
}
},
mounted() {
let img = new Image();
img.src = this.myImage;
console.log(img.naturalWidth, img.naturalHeight);
},
[...]
}

最新更新