轉載自:https://segmentfault.com/a/1190000005898538?utm_source=tuicool&utm_medium=referral
轉換工具
智圖 isparta
判斷瀏覽器支持webP
方法一:
function checkWebp() { try{ return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0); }catch(err) { return false; } } console.log(checkWebp()); // true or false
console.log(checkWebp()); // true or false
方法是在其他地方上看到的,我用trycatch改寫了一下
原理:
The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome 支持 image/webp.
方法二:
var d = document; var check = function() { var supportWebp; try { var ele = d.createElement('object'); ele.type = 'image/webp'; ele.innerHTML = '!'; d.body.appendChild(ele); //奇妙所在,如果瀏覽器支持webp,那么這個object是不可見的(offsetWidth為0), //否則就會顯示出來,有可視寬度. supportWebp = !ele.offsetWidth; d.body.removeChild(ele); }catch (err) { supportWebp = false; } return supportWebp; }
1.若使用場景是瀏覽器,可以:
JavaScript 能力檢測,對支持 WebP 的用戶輸出 WebP 圖片
使用 WebP 支持插件:WebPJS