webp图像格式
WebP图像格式
webp格式的图片如何在html中应用
webp格式的图片既然有那么多的好处,那么如何使用这种格式的图片?首先要考虑到兼容性,对于不支持webp格式的图片依然使用原来的方式, 对于支持webp格式的图片则使用新的格式。例如静态资源中包含了webp和img两个文件夹,分别是webp资源和png资源。对于同一个使用背景图的元素, 我们原先是这样设置的
.elem {
background-image: url(../img/bg1.png);
......
}但是我们想在要支持webp格式的,则现在有这样一种方法。先看一下结果:
[] .elem {
background-image: url(../img/bg1.png);
......
}
[] .elem {
background-image: url(../webp/bg1.webp);
......
}这种通过>代码是:
function isSupportWebp () {
// save the results supported by the browser
var flag = '0'
// get canvas element
var canvasEL = document.createElement('canvas')
// get html element
var docEl = document.documentElement || document.getElementsByTagName('html')[0]
// determine whether the browser supports canvas elements
if (canvasEL.getContext && canvasEL.getContext('2d')) {
flag = canvasEL.toDataURL('image/webp').indexOf('image/webp') > -1 ? '1' : '0'
}
// set data-webp attribute for html
docEl.setAttribute('data-webp', flag)
// return supported result
return flag
}
isSupportWebp()本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!