图片往往在加载前端项目中占大头,如何既不损失图片质量,又提升加载速度呢?
注册全局自定义指令
Vue.directive('img-condense', { bind: (el, binding, vnode) => { let src = el.getAttribute('src') let newSrc = compressImg(src, el) el.setAttribute('src', newSrc) } })
获取元素宽高和显示设备pixelRatio
let compressImg = (imgUrl, el) => { // 获取显示设备 pixelRatio let pixelRatio = window.devicePixelRatio let elWidth = elStyle.width * pixelRatio let elHeight = elStyle.height * pixelRatio let resize = '/resize' if (elWidth) { resize += `,w_${elWidth}` } if (elHeight) { resize += `,h_${elHeight}` } })
判断webp
let canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0 let webp = '' if (canUseWebp) { webp = '/format,webp' }
质量降低至80%
let ossParam?x-oss-process=image${resize}/auto-orient,1/quality,Q_80/bright,-1${webp}
完整版
<img v-img-condense alt="Vue logo" src="../assets/logo.png"> Vue.directive('img-condense', { bind: (el, binding, vnode) => { let src = el.getAttribute('src') let newSrc = compressImg(src, el) el.setAttribute('src', newSrc) } }) let compressImg = (imgUrl, el) => { // 如果不是oss 或者已经压缩过的图片直接返回 if (imgUrl.includes('aliyuncs.com') || imgUrl.indexOf('blob') === 0 || imgUrl.includes('x-oss-process=')){ return imgUrl } // 获取显示设备 pixelRatio let pixelRatio = window.devicePixelRatio let elWidth = el.width * pixelRatio let elHeight = el.height * pixelRatio let resize = '/resize' if (elWidth) { resize += `,w_${elWidth}` } if (elHeight) { resize += `,h_${elHeight}` } if (!elWidth && !elHeight) { resize = '' } // 判断webp let canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0 let webp = '' if (canUseWebp) { webp = '/format,webp' } return `${imgUrl}?x-oss-process=image${resize}/auto-orient,1/quality,Q_80/bright,-1${webp}` }
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!