UNPKG

2.93 kBJavaScriptView Raw
1var fs = require('fs');
2var path = require('path');
3var glob = require('glob');
4var Spritesmith = require('spritesmith');
5
6var id = 1;
7
8function getShareCss (o) {
9 return (
10`.${o.name} {
11 background-image: url(${o.url});
12 background-repeat: no-repeat;
13 background-size: ${o.sizeWidth}${o.unit} ${o.sizeHeight}${o.unit};
14}
15`
16 );
17}
18
19function getSpriteCss (o) {
20 return (
21`.${o.name} {
22 width: ${o.width}${o.unit};
23 height: ${o.height}${o.unit};
24 background-position: ${o.x}${o.unit} ${o.y}${o.unit};
25}
26`
27 );
28}
29
30/**
31 * 生成雪碧图及css
32 * @param {array} list
33 * list.src 需要生成雪碧图的图片源,支持glob查找
34 * list.dest 雪碧图的输出位置
35 * list.padding 合成图片的间距,默认0
36 * list.cssDest css的输出位置,默认和dest相同位置
37 * list.cssUrl css中url的定义,默认dest定义的位置
38 * list.cssUnit css中的像素单位,默认px
39 * @param {function} success(file)
40 */
41module.exports = function (list, success) {
42 if (!Array.isArray(list)) {
43 list = [list];
44 }
45
46 list.forEach(item => {
47 if (typeof item === 'string' || Array.isArray(item)) {
48 item = { src: item };
49 }
50
51 // 只支持png,jpg,jpeg
52 var files = (typeof item.src === 'string' ? glob.sync(item.src) : item.src).filter(file => /\.(png|jpe?g)(\?.*)?$/.test(file));
53
54 if (!files.length) return;
55
56 Spritesmith.run({
57 src: files,
58 padding: item.padding || 0
59 }, (err, result) => {
60 if (err) {
61 console.error(err);
62 return;
63 }
64
65 // result.image; // Buffer representation of image
66 // result.coordinates; // Object mapping filename to {x, y, width, height} of image
67 // result.properties; // Object with metadata about spritesheet {width, height}
68
69 var dest = item.dest || ('sprites-' + (id++) + '.png');
70 var cssDest = item.cssDest || dest.replace(/\.png$/, '.css');
71 var cssUnit = item.cssUnit || 'px';
72 var shareNames = path.basename(dest).split('.');
73 shareNames.splice(-1, 1);
74
75 var styles = [
76 getShareCss({
77 name: shareNames.join('_'),
78 url: item.cssUrl || dest,
79 sizeWidth: result.properties.width,
80 sizeHeight: result.properties.height,
81 unit: cssUnit
82 })
83 ];
84
85 Object.keys(result.coordinates).forEach((key, index) => {
86 var data = result.coordinates[key];
87 var names = path.basename(key).split('.');
88 names.splice(-1, 1, index + 1);
89
90 var cssData = {
91 name: 'sprite-' + names.join('_'),
92 x: data.x,
93 y: data.y,
94 width: data.width,
95 height: data.height,
96 unit: cssUnit
97 };
98 styles.push(getSpriteCss(cssData));
99 });
100
101
102 fs.writeFileSync(dest, result.image);
103 success && success(dest);
104
105 fs.writeFileSync(cssDest, styles.join('\n'));
106 success && success(cssDest);
107 });
108 });
109}