需求描述
仅一张gif动图,进入页面,呈现静态图片显示,点击,gif图显示。
代码实现
<el-image
style="width: 100px; height: 100px"
:src="props.data.row.thumbnail_url"
class="gif-img"
fit="contain"
/>
onMounted(async () => {
setTimeout(() => {
// 页面获取得到数据,渲染后再获取dom
// 如果还获取不到,得到数据后,再渲染页面(外层v-if)
handleStaticImg()
})
})
const handleStaticImg = () => {
const imgAllElement = document.querySelectorAll('.gif-img')
Array.from(imgAllElement).forEach((element) => {
// console.log(element.children[0], (element.children[0] as any).naturalHeight)
;(element.children[0] as any).onload = () => {
const imgElement = element.children[0] as any
if (imgElement.naturalHeight) {
const canvas = document.createElement('canvas') as any
// 尺寸
const naturalHeight = imgElement.naturalHeight
const naturalWidth = imgElement.naturalWidth
const rate = Math.max(naturalHeight, naturalWidth) / 100
const width = naturalWidth / rate,
height = naturalHeight / rate
if (width && height) {
// canvas大小
canvas.width = width
canvas.height = height
// 绘制图片帧(第一帧)
canvas.getContext('2d').drawImage(imgElement, 0, 0, width, height)
// 重置当前图片
try {
imgElement.src = canvas.toDataURL('image/gif')
} catch (e) {
// 跨域
console.log(e)
// 隐藏原图
imgElement.style.display = 'none'
// 载入canvas元素
canvas.style = 'position:absolute;top:0;bottom:0;margin:auto;left:0'
// 前面插入图片
imgElement.parentElement.insertBefore(canvas, imgElement)
// 存储canvas
imgElement.storeCanvas = canvas
canvas.addEventListener('click', (event: any) => {
event.path[1].children[1].style.display = 'inline-block'
})
}
}
}
}
})
// console.log(imgAllElement)
}