gpt4 book ai didi

javascript - 为什么这个 WebP 支持函数每次运行时都会返回随机结果?

转载 作者:行者123 更新时间:2023-11-30 20:22:30 25 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - 为什么这个 WebP 支持函数每次运行时都会返回随机结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com