此demo的示例代码参考于giffer插件,地址:www.jq22.com/jquery-info…
废话不多说,直接上代码: html部分:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.img {
display:none;
width:100px;
height:100px;
background-size:100%;
border:2px solid black;
}
.active {
display:block
}
.canvas {
border:3px solid blue;
}
</style>
</head>
<body>
<img data-gifffer="./fish.gif" class="image-big"/>
<script src="gifffer.js"></script>
<script>
window.onload = function() {
Gifffer();
}
</script>
</body>
</html>
复制代码
js部分
var Gifffer = function() {
var images, d = document, ga = 'getAttribute', sa = 'setAttribute';
images = d && d.querySelectorAll ? d.querySelectorAll('[data-gifffer]') : [];
var createContainer = function(w, h, el) {
var con = d.createElement('DIV'), cls = el[ga]('class'), id = el[ga]('id');
cls ? con[sa]('class', el[ga]('class')) : null;
id ? con[sa]('id', el[ga]('id')) : null;
con[sa]('style', 'position:relative;cursor:pointer;width:' + w + 'px;height:' + h + 'px;');
el.parentNode.replaceChild(con, el);
return {c: con};
}
var process = function(el) {
var url, con, c, w, h, play, gif, playing = false, cc, isC;
url = el[ga]('data-gifffer');
w = el[ga]('data-gifffer-width');
h = el[ga]('data-gifffer-height');
el.style.display = 'block';
c = document.createElement('canvas');
isC = !!(c.getContext && c.getContext('2d'));
if(w && h && isC) cc = createContainer(w, h, el);
el.onload = function() {
if(isC) {
w = w || el.width;
h = h || el.height;
// creating the container
if(!cc) cc = createContainer(w, h, el);
con = cc.c;
// canvas
c.width = w;
c.height = h;
c.getContext('2d').drawImage(el, 0, 0, w, h);
con.appendChild(c);
con.addEventListener('mouseenter', function() {
setTimeout(function(){
if(!playing) {
playing = true;
gif = d.createElement('IMG');
gif[sa]('style', 'width:' + w + 'px;height:' + h + 'px;');
gif[sa]('data-uri', Math.floor(Math.random()*100000) + 1);
setTimeout(function() {
gif.src = url;
}, 0);
con.removeChild(c);
con.appendChild(gif);
}
},300,false);
});
con.addEventListener('mouseout', function() {
if(playing){
playing = false;
con.removeChild(gif);
con.appendChild(c);
gif = null;
}
});
}
}
el.src = url;
}
for(var i=0; i<images.length; i++) process(images[i]);
复制代码
}
大概原理就是:获取属性为data-gifffer的img图片,创建一个外层容器的div,即代码中的createContainer函数的作用,在外层容器div中,绘制canvas,在canvas中drawImage,这可以让gif静止,当鼠标悬浮到canvas时,创建img用于gif,并将其添加到外层容器div中,同时移除canvas,鼠标移走时,反之亦可。