super-fool / blog

珍藏经典, 分享思想, 共同进步.加油
3 stars 0 forks source link

什么是WebP #57

Open super-fool opened 4 years ago

super-fool commented 4 years ago

WebP是谷歌推出的一种图片格式,在压缩方面比当前JPEG格式更优越。

它是一种有损压缩的图片格式, 但是更高效

它的优势在于:更高效,因为体积要比JPEG格式图像小40%。

一般我们可以用在头像,缩略图等地方。

super-fool commented 4 years ago

首先,这种格式主要用于Chrome浏览器。

为了兼容IE,有两种使用方式:

  1. 判断加载WebP图片的宽高是否能获取到
var img = new Image();

img.onload = function() {
  var isWebP = !!(img.height > 0 && img.width > 0);
  checkWebP(isWebP);
}

img.onerror = function() {
 checkWebP(isWebP);
}

function checkWebP(isWebP) {
  var imgs = document.getElementsByTagName('img');
  [...img].forEach( ele=>{
      var webpSrc = ele.dataset.webp;  // 获取WebP格式图片的src
      var picSrc = ele.dataset.pic; // 获取普通的jpeg格式图片的src
      var src = !!isWebP ? webpSrc : picSrc;
      ele.setAttribute( 'src', 'src');
    }
  )
}
super-fool commented 4 years ago
  1. 第二种方法:
    var checkWebp = function(){
    try{
        return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0);
    }catch(err) {
        return  false;
    }
    }
    isWebP = checkWebP() //isWebP为true则支持WebP,若为false则不支持WebP
super-fool commented 4 years ago

插件: imagemin-webp