【问题标题】:Why is Chrome reporting an old NaturalWidth for an Image object?为什么 Chrome 会报告 Image 对象的旧 NaturalWidth?
【发布时间】: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


【解决方案1】:

好吧,我找到了解决问题的方法。由于某些原因,我仍然不确定从从目标背景图像中获取图像创建的图像中提取宽度/高度数据会导致问题。我重写了直接获取图片URL的方法,现在可以正常使用了

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多