为什么此WebP支持功能每次运行都会返回随机结果?

时间:2018-07-12 18:45:41

标签: javascript function webp

我正在尝试创建一段代码,该代码确定浏览器是否支持WebP图像,然后确定它是否加载JPEG或WebP。似乎每次浏览器刷新时都会随机返回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;
}

首次运行时,它返回false,但是如果我稍后运行它,则返回true。为什么会这样?

(我正在使用最新版本的Chrome Canary,并且还在最新的Google Chrome版本中尝试过该功能)

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

1 个答案:

答案 0 :(得分:1)

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()