【问题标题】:Why does this WebP Support function return random results each time it's run?为什么这个 WebP Support 函数每次运行时都会返回随机结果?
【发布时间】:2018-07-13 03:22:19
【问题描述】:

我正在尝试创建一段代码来确定浏览器是否支持 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) 像素组成。

【问题讨论】:

  • 如果在函数中循环两次drawImage()函数,第二次检查数据会怎样?在那种情况下,这总是会返回 true 吗?也许使用 webp 图像调用 toDataURL 存在一些不确定性?您需要这样做似乎很奇怪,看来您确实需要借助 hack 来使其保持一致。
  • 仅供参考,Firefox支持 webp
  • @SamuelCook 他们确实没有

标签: javascript function webp


【解决方案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()

【讨论】:

  • @DavidWheatley,很乐意为您提供帮助!
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2018-05-02
相关资源
最近更新 更多