1 | var fs = require('fs');
|
2 | var path = require('path');
|
3 | var glob = require('glob');
|
4 | var Spritesmith = require('spritesmith');
|
5 |
|
6 | var id = 1;
|
7 |
|
8 | function 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 |
|
19 | function 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 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | module.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 |
|
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 |
|
66 |
|
67 |
|
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 | }
|