基于Compass+Sass实现函数式自动生成逐帧动画,先安装Compass和Sass
// gem安装依赖于ruby
gem install compass
gem install sass
@import "compass";
@function pxToRem ($value){
$value : removePx($value);
@return $value / 20 * 1rem;
}
// 去单位px
@function removePx ($value){
$value : $value / ($value * 0 + 1);
@return $value;
}
// 计算并给每一帧动画赋值宽高及背景图坐标
@mixin retinaSprite($sprite, $name){
width: pxToRem(image-width(sprite-file($sprite, $name)));
height: pxToRem(image-height(sprite-file($sprite, $name)));
// $xpos: pxToRem(round(nth(sprite-position($sprite, $name), 1)));
// $ypos: pxToRem(round(nth(sprite-position($sprite, $name), 2)));
// background-position: $xpos $ypos;
$ypos: removePx((round(nth(sprite-position($sprite, $name), 2)) / (sprite-height($sprite) - image-height(sprite-file($sprite, $name)))) * -1)* 100%;
background-position: 0% $ypos;
}
@mixin retinaAnimation($sprite, $delay:false){
$list: sprite-names($sprite);
$length: length($list);
$progress: 0;
$per: 0;
@if $delay{
$per: 50/$length;
$progress: 50+$per;
}@else{
$per: 100/$length;
$progress: $per;
}
@keyframes #{sprite-map-name($sprite)}{
@each $name in $list{
#{$progress}%{
@include retinaSprite($sprite, $name);
}
$progress: $progress+$per;
}
}
}
将一个逐帧动画的所有帧图片放到一个文件夹中,注意每一帧图片的宽高要保持一致,比如说要实现一个小狗的逐帧动画,咱们把所有的帧图片都放到一个dog
文件夹里面
$dog: sprite-map("dog/*.png", $layout : 'vertical');
.ani{
background: $dog no-repeat;
background-size: pxToRem(round(image-width(sprite-path($dog)))) auto;
@include retinaAnimation($dog, $delay:true);
animation: #{sprite-map-name($dog)} 2s step-start infinite both;
}
以今年618账单为例,首先git clone
本项目,
cd autoFBF/
cnpm install
// 开启本地服务:npm start,命令的具体含义可以在package.json中查看
npm start
新建命令行窗口,开启compass监控
cd src/
compass watch
修改sprite.scss,将注释掉的部分代码取消注释
.firstTime{
.ani{
background: $dog no-repeat;
background-size: pxToRem(round(image-width(sprite-path($dog)))) auto;
@include retinaAnimation($dog, $delay:true);
animation: #{sprite-map-name($dog)} 2s step-start infinite both;
}
}
.manyTimes{
.ani{
background: $toothBrush no-repeat;
background-size: pxToRem(round(image-width(sprite-path($toothBrush)))) auto;
@include retinaAnimation($toothBrush, $delay:true);
animation: #{sprite-map-name($toothBrush)} 2s step-start infinite both;
}
}
可以看到compass
监控到了变化,并合成了雪碧图
在img
文件夹中看到合成的图片
sprite.css
被写入了逐帧动画
再查看 http://localhost:8080
,由于webpack的热更新,我们能够直接看到逐帧动画了