获取图片信息
这里我们默认根据第一张图片的尺寸信息作为外层DIV的默认尺寸。
#!/usr/bin/env node const program = require('commander'); const fs = require('fs'); const path = require('path'); const createHTML = require('create-html'); const sizeOf = require('image-size'); const chalk = require('chalk'); program.version('1.0.0', '-v, --version') .command('start <dir>') .action((dir) => { //获取图片路径 const imgPath = path.resolve(dir) let imgSize = null; fs.readdir(imgPath, (err, file) => { imgSize = sizeOf(dir + '/' +file[0]); //取第一个图片的尺寸作为框尺寸 let cssString = ` .fbf-animation{ width: ${imgSize.width}px; height: ${imgSize.height}px; margin:auto; background-image: url(./${dir}/${file[0]}); background-size: ${imgSize.width}px ${imgSize.height}px; background-repeat: no-repeat; animation-name: keyframes-img; animation-duration: 0.36s; animation-delay: 0s; animation-iteration-count: infinite; animation-fill-mode: forwards; animation-timing-function: steps(1); } ` }) })
生成CSS代码
然后根据图片数量生成相应的keyframes代码
function toCss(dir, fileList){ let _css = ''; let start = 0; const per = Math.floor(100/fileList.length); fileList.map((path, i) => { if(i === fileList.length - 1){ _css += ` ${start + i*per}%, 100% { background:url(./${dir}/${path}) center center no-repeat; background-size:100% auto; } ` }else{ _css += ` ${start + i*per}% { background:url(./${dir}/${path}) center center no-repeat; background-size:100% auto; } ` } }) return _css; } let frameCss = toCss(dir, newFile) //取第一个图片的尺寸作为框尺寸 let cssString = ` .fbf-animation{ width: ${imgSize.width}px; height: ${imgSize.height}px; margin:auto; background-image: url(./${dir}/${file[0]}); background-size: ${imgSize.width}px ${imgSize.height}px; background-repeat: no-repeat; animation-name: keyframes-img; animation-duration: 0.36s; animation-delay: 0s; animation-iteration-count: infinite; animation-fill-mode: forwards; animation-timing-function: steps(1); } @keyframes keyframes-img { ${frameCss} }
生成html文件
最后我们把生成的CSS放到HTML里。
//生成html let html = createHTML({ title: '逐帧动画', scriptAsync: true, lang: 'en', dir: 'rtl', head: '<meta name="description" content="example">', body: '<div class="fbf-animation"></div>' + css, favicon: 'favicon.png' }) fs.writeFile('fbf.html', html, function (err) { if (err) console.log(err) })
视觉美化
通过 chalk 来为打印信息加上样式,比如成功信息为绿色,失败信息为红色,这样子会让用户更加容易分辨,同时也让终端的显示更加的好看。
const chalk = require('chalk'); console.log(chalk.green('生成代码成功!')); console.log(chalk.red('生成代码失败'));