逐帧动画效果
- css方式
// css 部分
.comp_img_ani{
width: 220px;
height: 220px;
margin: auto;
background: url("../../static/dev_img/yellow-starts.png") no-repeat; // 帧动画一定要使用背景图片
animation: imgAnimation 0.6s step-end infinite; // 这里的infinite 为必须
/*animation-iteration-count: 6;*/ // 执行次数
}
@keyframes imgAnimation {
0%{background-position: calc(-187.5px * 0);}
20%{background-position:calc(-187.5px * 1);}
40%{background-position:calc(-187.5px * 2);}
60%{background-position:calc(-187.5px * 3);}
80%{background-position:calc(-187.5px * 4);}
100%{background-position: calc(-187.5px * 0);}
}
// javascript部分
setCss(){
function getDom(){
let imageDom = document.getElementsByClassName('comp_img_ani')[0];
if(imageDom) {
if(imageDom.style.animationPlayState==='running'){
imageDom.style.animationPlayState = 'paused'; // 暂停animation
}else {
imageDom.style.animationPlayState = 'running'; // 继续animation
}
clearInterval(domTiemr);
};
}
let domTiemr = setInterval(getDom, 100)
},
- js + css方式
// css 部分,其中dom的图片也是background-image
.comp_img_ani{
width: 220px;
height: 220px;
margin: auto;
background: url("../../static/dev_img/yellow-starts.png") no-repeat;
}
// yellow-starts 位置信息
let numAndDistance = {
maxNumber: 11,
image: require("@/static/dev_img/yellow-starts.png"),
closePage: true,
1: {x:-220 * 0, y:0},
2: {x:-220 * 1, y:0},
3: {x:-220 * 2, y:0},
4: {x:-220 * 3, y:0},
5: {x:-220 * 4, y:0},
6: {x:-220 * 5, y:0},
7: {x:-220 * 6, y:0},
8: {x:-220 * 7, y:0},
9: {x:-220 * 8, y:0},
10: {x:-220 * 9, y:0},
11: {x:-220 * 10, y:0},
};
/*
* @description
* 参数:1.className为id或者class用来获取dom; 2.maxNumber为移动次数(大于零);3.numAndDistance 为平移的位置信息,以及移动次数,图片地址,是否由本动画关闭当前页面(自动关闭page)
* */
animateImg(className, maxNumber,numAndDistance ){
let that = this;
let startT = new Date().getTime();
let oldT, newT;
let number = 1;
let imageDom, frameId;
let getImgDom = function(){
imageDom = document.getElementsByClassName(className)[0];
if(imageDom) {
oldT = new Date().getTime();
frameId = requestAnimationFrame(imgAnimate);
clearInterval(domTiemr);
};
};
let domTiemr = setInterval(getImgDom(), 100);
function imgAnimate(){
oldT = new Date().getTime();
if (number>maxNumber){
if(numAndDistance.closePage){
that.compImgStatus = !that.compImgStatus;
}
window.cancelAnimationFrame(frameId);
return ;
};
imageDom.style.backgroundPosition = numAndDistance[number].x + 'px';
newT = new Date().getTime();
console.warn("执行次序:", number, ", 帧时间间隔:", newT - oldT,"ms, 总耗时:", newT - startT);
number++;
// 使用延时器减缓动画的速度
let timerOut = setTimeout(()=>{
requestAnimationFrame(imgAnimate);
clearTimeout(timerOut);
}, 100)
}
},
注意, 设置background-repeat后,关于x和y的值可能发生正负的变化。暂时没有查明原因。
requestAnimationFrame()的循环执行帧动画,存在动画后期执行很快的问题。暂时没有查明原因。
通过图片集合在线生成精灵图png的网站
https://www.toptal.com/developers/css/sprite-generator/
这个可以辅助,暂时没用明白
http://www.spritecow.com/