Javascript 为什么Chrome报告图像对象的旧自然宽度?

Javascript 为什么Chrome报告图像对象的旧自然宽度?,javascript,google-chrome,chromium,Javascript,Google Chrome,Chromium,是的,所以我99%肯定这是Chrome(和Edge等)中一个令人讨厌的bug,因为它在Firefox中工作得非常完美。无论如何,我有一个类,它有一个图像对象,它会不时地改变源,我需要使用图像的NaturalWidth和NaturalHeight属性。问题是,当图像源更改时,Chrome不会更新这些属性。只有在随后的源更改中,它们才会更改,并且它们将更改为当前加载的图像之前的图像-_- class Pictura { constructor(target) { this

是的,所以我99%肯定这是Chrome(和Edge等)中一个令人讨厌的bug,因为它在Firefox中工作得非常完美。无论如何,我有一个类,它有一个图像对象,它会不时地改变源,我需要使用图像的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图像对象

我试着创建一个新的图像对象,而不是循环使用现有的图像对象,没有什么区别。我还尝试创建Pictura类的一个新实例,Chrome仍然使用以前加载的图像的高度和宽度属性,即使该图像属于该类的一个完全不同的实例


发生了什么事?

我找到了解决问题的办法。由于某些原因,我仍然不确定从从目标背景中获取图像创建的宽度/高度数据是否会导致问题。我已经重写了直接获取图像URL的方法,现在它工作正常了

嘿,你能包括使用
自然高度的部分代码吗
?在这个例子中,记录了400和300:添加了一个使用自然高度的方法