问题描述
是的,因此,我大约99%确信这是Chrome(和Edge等)中的烦人错误,因为它在Firefox中可完美运行。无论如何,我有一个具有Image对象的类,该对象会不时更改源,并且我需要使用图像的NaturalWidth和NaturalHeight属性。问题是,当图像源更改时,Chrome不会更新这些属性。只有在随后的源更改中,它们才会更改,并且它们将更改为当前加载的图像之前的-_-
class Pictura {
constructor(target) {
this.container = target;
this.canvas = new Image;
this.containerStyle = window.getComputedStyle(this.container,false);
}
load() {
this.canvas.src = this.containerStyle.backgroundImage.slice(4,-1).replace(/"/g,"");
this.canvas.onload = function() {
this.container.addEventListener('pointermove',this.pan.bind(this));
this.container.addEventListener('pointerout',this.default.bind(this));
this.default();
}.bind(this);
}
pan(e) {
e.preventDefault();
console.log(this.canvas.naturalWidth);
let xPos = numberRange(e.offsetX,this.container.clientWidth),yPos = numberRange(e.offsetY,this.container.clientHeight);
let xPercent = (this.canvas.naturalWidth > this.container.clientWidth
? xPos / this.container.clientWidth * 100 + '%'
: '50%');
let yPercent = (this.canvas.naturalHeight > this.container.clientHeight
? yPos / this.container.clientHeight * 100 + '%'
: '50%');
Object.assign(this.container.style,{
backgroundPosition: xPercent + ' ' + yPercent,backgroundSize: this.canvas.naturalWidth + 'px ' + this.canvas.naturalHeight + 'px'
});
this.container.classList.add('static');
}
...
这是有问题的代码。更改背景图像时将调用load()方法,然后使用新的背景图像更新this.canvas图像对象。
我尝试创建一个新的Image对象,而不是回收现有的对象,这没有什么不同。我也尝试过创建Pictura类的新实例,尽管该图像属于该类的完全不同的实例,但Chrome仍使用以前加载的图像的height和width属性。
这是怎么回事?
解决方法
我想出了解决问题的方法。由于某些原因,我仍不确定要从通过从目标backgroundimage采购图像而获得的图像中提取宽度/高度数据会导致问题。我已经重写了直接获取图片网址的方法,现在它可以正常工作