为什么这个 WebP 支持函数 return 每次都是 运行 随机结果?

Why does this WebP Support function return random results each time it's run?

我正在尝试创建一段代码来确定浏览器是否支持 WebP 图像,然后确定它是加载 JPEG 还是 WebP。每次浏览器刷新时似乎随机 return true 和 false。

function supportsWebP() {
    var img = new Image();
    img.src = "/img/test-img.png";

    var canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth; // or 'width' if you want a special/scaled size
    canvas.height = img.naturalHeight; // or 'height' if you want a special/scaled size

    canvas.getContext('2d').drawImage(img, 0, 0);

    var data = canvas.toDataURL('image/webp');
    if (data.startsWith("data:image/webp")) { // Will start with "data:image/png" if unsupported
        console.info("WebP is supported by your browser.");
        return true;
    }

    console.warn("WebP is NOT supported by your browser. Consider upgrading to Chrome/updating your browser version");
    return false;
}

当它是第一个 运行 时,它 return 是 false 但如果我稍后 运行 它,它 return 是真的。这是为什么?

(我在最新版本上使用 Chrome Canary,也在最新的 Google Chrome 版本上尝试过)

编辑:test-img.png 是一个 1px x 1px 图像,仅由 100% 黑色 (#000000) 像素组成。

src 应用到 image 需要一些时间,因此请使用 onload 侦听器:

function supportsWebP() {
  var img = new Image();
  img.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAgT/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCoAEhf/9k=";
  
  img.onload = () => {
    var canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth; // or 'width' if you want a special/scaled size
    canvas.height = img.naturalHeight; // or 'height' if you want a special/scaled size

    canvas.getContext('2d').drawImage(img, 0, 0);

    var data = canvas.toDataURL('image/webp');
    if (data.startsWith("data:image/webp")) { // Will start with "data:image/png" if unsupported
      console.info("WebP is supported by your browser.");
      return true;
    }

    console.warn("WebP is NOT supported by your browser. Consider upgrading to Chrome of Firefox/updating your browser version");
    return false;
  }
}


supportsWebP()