[英]Get height/width of image in Javascript (ideally without loading the image at all)
[英]get actual width/height of an image without loading the image into the page with javascript
我想知道是否有可能在不将图像放入页面的情况下(即不创建显示图像的图像标签)获得图像的宽度和高度。
尝试使用此方法制作Sprite类。
function Sprite(src,frames) {
// Sprite class
this.img = new Image();
this.img.src = src;
this.frames = frames;
this.cframe = 1;
this.setDim = function() {
this.fullWidth = this.img.width;
this.fullHeight = this.img.height;
}
this.img.onload = this.setDim();
console.log(this.fullWidth);
return this;
}
但是this.fullWidth
返回undefined,下面的忽略onload的返回0
function Sprite(src,frames) {
// Sprite class
this.img = new Image();
this.img.src = src;
this.frames = frames;
this.cframe = 1;
this.fullWidth = this.img.width;
this.fullHeight;
this.setDim = function() {
this.fullWidth = this.img.naturalWidth;
this.fullHeight = this.img.height;
console.log(this.fullWidth)
}
console.log(this.fullWidth)
//this.img.onload = this.setDim();
return this;
}
我真的不想为此使用Jquery。 我也尝试过this.img.natrualWidth
(如您在上面的示例中看到的),它也返回0
任何建议都很好,谢谢
更新了此内容以匹配@ vihan1086答案
function Sprite(src,frames) {
// Sprite class
this.img = new Image();
this.img.src = src;
this.frames = frames;
this.cframe = 1;
var self = this;
self.loaded = function () {};
this.setDim = function() {
self.fullWidth = this.width;
self.fullHeight = this.height;
self.frameWidth = this.width / self.frames;
self.frameHeight = this.height;
self.loaded.apply(self, []);
}
this.loaded = function() {
return this;
}
this.img.onload = this.setDim;
}
然后使用
sprite = new Sprite(sprite,5);
sprite.loaded = function() {
console.log(sprite.fullWidth);
}
var img = new Image();
img.src = '/my/src/to/file';
//this refers to the current function at this point
img.onload = function () {
//this is 'img' at this point not the function
}
this
不在范围内,因此您应该添加:
var self = this;//Self and this are referring to the same thing, the function
img.onload = function () {
//this refers to image but self still refers to the function's this
self.width = this.width;
self.height = this.height;
}
console.log(this.width);//logs width
console.log(this.height);//logs height
这留下了异步问题,可以使用两种方法解决
一种
this.img.onload = this.setDim; //Noticed the dropped ()
乙
self.loaded = function () {};
this.setDim = function () {
//...
self.loaded.apply(self, []);
}
然后
var sprite = new Sprite(...);
sprite.loaded = function () {
console.log(this.fullHeight);
}
img.onload()
更改代码的范围,从而导致你的this
指的是img
。 现在很奇怪。 我们创建了一个变量self
来引用this
,这允许我们使用self
在不同的范围内引用this
。
img.onload
是“异步的”,这意味着它不会与其余代码一起出现。 这意味着console.log()
已运行,但img.onload
没有运行。 使用这种类型的代码时要小心(我在更新中写了一些解决方案) 。 您应该等到img.onload
完成之后再检查这些值。 之前,我已经进行过类似的工作,然后看看是否可以找到解决所有这些问题的方法。 如果可以,我将更新此答案。
更新 :我不会先运行setDim
函数,而让用户运行setDim()
-> setDim
。 如果您希望首先加载尺寸,则将加载函数放到Sprite()
,该功能将在检索尺寸时运行。
在javascript中,这些语句是异步执行的。 要了解更多有关此内容的信息,请阅读这篇出色的文章:在函数内部修改变量后,为什么变量没有改变? -异步代码参考
在您的情况下@Juhana提到传递引用应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.