【发布时间】:2020-09-02 11:15:17
【问题描述】:
是的,所以我大约 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, 0, this.container.clientWidth),
yPos = numberRange(e.offsetY, 0, 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 仍然使用先前加载的图像的高度和宽度属性,即使该图像属于该类的完全不同的实例。
发生了什么事?
【问题讨论】:
-
嘿,你能把使用
naturalHeight的部分代码包括进来吗? -
在本例中记录了 400 和 300:jsfiddle.net/wbmp2sLr
-
添加了一个使用 naturalHeight 的方法
标签: javascript google-chrome chromium