效果:gif一開始是靜態(tài)的,點擊后才播放
參考效果:微博 貼吧 ……
demo基于vue框架,功能實現主要用原生js
<template>
<img :src="imgblob||(src+'?time=' + new Date().valueOf())" alt="" @load="read($event)" ref="img" crossorigin="anonymous">
</template>
<script>
export default {
props: {
src: {
type: String,
default: ''
}
},
data(){
return{
imgblob:null
}
},
methods: {
read(e) {
let image = e.path[0];//獲取img節(jié)點吟吝,建議用ref方式
let canvas = document.createElement("canvas"); //創(chuàng)建畫布
canvas.width = image.width;
canvas.height = image.height; //設定寬高比
canvas.getContext('2d').drawImage(image, 0, 0, canvas.width, canvas.height); //將gif此刻幀數畫入畫布
this.imgblob = canvas.toDataURL("image/png");//將canvas轉成資源url
}
}
}
</script>
<style>
</style>
注意:
crossorigin="anonymous"這個屬性有什么用
使用跨域資源菱父,canvas轉成資源url時會報安全錯誤
image.png
此時<img/>要添加crossorigin="anonymous"屬性聲明這是跨域請求資源
詳細:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/img#attr-crossorigin
為什么要在資源后面加個時間戳 '?time=' + new Date().valueOf()
上面的安全錯誤解決了,但是服務端并沒有無條件允許全部請求,資源請求失敗
解決方法也很簡單浙宜,補個條件('?time=' + new Date().valueOf())就是了官辽,服務器怎么處理是它的事。
解決方案參考:https://segmentfault.com/q/1010000008648867