UNPKG

29.6 kBMarkdownView Raw
1# gulp.spritesmith [![Build status](https://travis-ci.org/twolfson/gulp.spritesmith.svg?branch=master)](https://travis-ci.org/twolfson/gulp.spritesmith) [![Subscribe to newsletter](https://img.shields.io/badge/newsletter-subscribe-blue.svg)](http://eepurl.com/bD4qkf)
2
3Convert a set of images into a spritesheet and CSS variables via [gulp][]
4
5This is the official port of [grunt-spritesmith][], the [grunt][] equivalent of a wrapper around [spritesmith][].
6
7[gulp]: http://gulpjs.com/
8[grunt-spritesmith]: https://github.com/Ensighten/grunt-spritesmith
9[grunt]: http://gruntjs.com/
10[spritesmith]: https://github.com/Ensighten/spritesmith
11
12![Example input/output](docs/example.png)
13
14Alternative output formats include [SASS, Stylus, LESS, and JSON][css-formats].
15
16[css-formats]: #spritesmithparams
17
18### Retina support
19As of `gulp.spritesmith@3.5.0`, retina spritesheets/templates are supported. See the [Retina parameters section](#retina-parameters) for more information.
20
21### Do you like `gulp.spritesmith`?
22[Support us via donations][support-us] or [spread word on Twitter][twitter]
23
24[support-us]: http://bit.ly/support-spritesmith2
25[twitter]: https://twitter.com/intent/tweet?text=CSS%20sprites%20made%20easy%20via%20gulp.spritesmith&url=https%3A%2F%2Fgithub.com%2Ftwolfson%2Fgulp.spritesmith&via=twolfsn
26
27## Breaking changes in 4.0.0
28We are normalizing sprite variables even further to convert any non-alphanumeric/non-dash/non-underscore character to a delimiter character (e.g. `-`). This allows us to support naming retina sprites with `@2x` suffixes, to prevent regressions like [grunt-spritesmith#137][].
29
30[grunt-spritesmith#137]: https://github.com/Ensighten/grunt-spritesmith/issues/137
31
32## Breaking changes in 5.0.0
33We have moved from [spritesmith-engine-spec@1.1.0][] to [spritesmith-engine-spec@2.0.0][]. This means if you use an custom engine (e.g. `gmsmith`, `canvassmith`), then you will need to upgrade it.
34
35```bash
36npm install my-engine-smith@latest --save-dev
37```
38
39This is enables us to use streaming outputs from engines in a future release.
40
41Additionally, we have added support for `buffer` and `stream` content for in-memory engines (e.g. `pixelsmith`, `canvassmith`) which resolves [#53][].
42
43[spritesmith-engine-spec@1.1.0]: https://github.com/twolfson/spritesmith-engine-spec/tree/1.1.0
44[spritesmith-engine-spec@2.0.0]: https://github.com/twolfson/spritesmith-engine-spec/tree/2.0.0
45[#53]: https://github.com/twolfson/gulp.spritesmith/issues/53
46
47## Breaking changes in 6.0.0
48We have completed our integration with streaming outputs from engines. As a result, [Vinyl][] `img` files will have `stream` contents which were previously buffers.
49
50If your `img` pipeline requires `Buffer` contents, then this can be remedied via [vinyl-buffer][]:
51
52```js
53// Throws error due to not supporting streams
54spriteData.img.pipe(imagemin());
55
56// Back to operational
57var buffer = require('vinyl-buffer');
58spriteData.img.pipe(buffer()).pipe(imagemin());
59```
60
61[vinyl-buffer]: https://github.com/hughsk/vinyl-buffer
62
63## Getting Started
64Install the module with: `npm install gulp.spritesmith`
65
66```js
67var gulp = require('gulp');
68var spritesmith = require('gulp.spritesmith');
69
70gulp.task('sprite', function () {
71 var spriteData = gulp.src('images/*.png').pipe(spritesmith({
72 imgName: 'sprite.png',
73 cssName: 'sprite.css'
74 }));
75 return spriteData.pipe(gulp.dest('path/to/output/'));
76});
77```
78
79### Continuing the pipeline
80In addition to the `spriteData` stream, we offer individual streams for images and CSS. This allows for image optimization and CSS minification.
81
82```js
83var gulp = require('gulp');
84var buffer = require('vinyl-buffer');
85var csso = require('gulp-csso');
86var imagemin = require('gulp-imagemin');
87var merge = require('merge-stream');
88
89var spritesmith = require('gulp.spritesmith');
90
91gulp.task('sprite', function () {
92 // Generate our spritesheet
93 var spriteData = gulp.src('images/*.png').pipe(spritesmith({
94 imgName: 'sprite.png',
95 cssName: 'sprite.css'
96 }));
97
98 // Pipe image stream through image optimizer and onto disk
99 var imgStream = spriteData.img
100 // DEV: We must buffer our stream into a Buffer for `imagemin`
101 .pipe(buffer())
102 .pipe(imagemin())
103 .pipe(gulp.dest('path/to/image/folder/'));
104
105 // Pipe CSS stream through CSS optimizer and onto disk
106 var cssStream = spriteData.css
107 .pipe(csso())
108 .pipe(gulp.dest('path/to/css/folder/'));
109
110 // Return a merged stream to handle both `end` events
111 return merge(imgStream, cssStream);
112});
113```
114
115## Documentation
116`gulp.spritesmith` presents the `spritesmith` function as its `module.exports`.
117
118### `spritesmith(params)`
119[gulp][] plugin that returns a [transform stream][] with 2 [readable stream][] properties.
120
121The input/output streams interact with [Vinyl][] objects which are [gulp's][gulp] format of choice.
122
123[transform stream]: http://nodejs.org/api/stream.html#stream_class_stream_transform
124[readable stream]: http://nodejs.org/api/stream.html#stream_class_stream_readable
125[Vinyl]: https://github.com/gulpjs/vinyl
126
127- params `Object` - Container for `gulp.spritesmith` parameters
128 - imgName `String` - Filename to save image as
129 - Supported image extensions are `.png` and `.jpg/jpeg` (limited to specfic engines)
130 - Image format can be overridden via `imgOpts.format`
131 - cssName `String` - Filename to save CSS as
132 - Supported CSS extensions are `.css` (CSS), `.sass` ([SASS][]), `.scss` ([SCSS][]), `.less` ([LESS][]), `.styl/.stylus` ([Stylus][]), and `.json` ([JSON][])
133 - CSS format can be overridden via `cssFormat`
134 - imgPath `String` - Optional path to use in CSS referring to image location
135 - padding `Number` - Optional amount of pixels to include between images
136 - By default we use no padding between images (`0`)
137 - An example usage can be found in the [Examples section](#padding)
138 - algorithm `String` - Optional method for how to pack images
139 - By default we use `binary-tree`, which packs images as efficiently as possible
140 - An example usage can be found in the [Examples section](#algorithm)
141 - More information can be found in the [Algorithms section](#algorithms)
142 - algorithmOpts `Object` - Options to pass through to algorithm
143 - For example we can skip sorting in some algorithms via `{algorithmOpts: {sort: false}}`
144 - This is useful for sprite animations
145 - See your algorithm's documentation for available options
146 - https://github.com/twolfson/layout#algorithms
147 - engine `String` - Optional image generating engine to use
148 - By default we use `pixelsmith`, a `node` based engine that supports all common image formats
149 - Alternative engines must be installed via `npm install`
150 - An example usage can be found in the [Examples section](#engine)
151 - More information can be found in the [Engines section](#engines)
152 - engineOpts `Object` - Options to pass through to engine for settings
153 - For example `phantomjssmith` accepts `timeout` via `{engineOpts: {timeout: 10000}}`
154 - See your engine's documentation for available options
155 - imgOpts `Object` - Options to pass through to engine uring export
156 - For example `gmsmith` supports `quality` via `{imgOpts: {quality: 75}}`
157 - See your engine's documentation for available options
158 - cssFormat `String` - CSS format to use
159 - By default this is the format inferred by `cssName's` extension
160 - For example `.styl -> stylus`
161 - For more format options, see our formatting library
162 - https://github.com/twolfson/spritesheet-templates#templates
163 - cssTemplate `String|Function` - CSS template to use for rendering output CSS
164 - This overrides `cssFormat`
165 - If a `String` is provided, it must be a path to a [handlebars][] template
166 - An example usage can be found in the [Examples section](#handlebars-template)
167 - If a `Function` is provided, it must have a signature of `function (data)`
168 - An example usage can be found in the [Examples section](#template-function)
169 - For more templating information, see the [Templating section](#templating)
170 - cssHandlebarsHelpers `Object` - Container for helpers to register to [handlebars][] for our template
171 - Each key-value pair is the name of a [handlebars][] helper corresponding to its function
172 - For example, `{half: function (num) { return num/2; }` will add a [handlebars][] helper that halves numbers
173 - cssVarMap `Function` - Mapping function for each filename to CSS variable
174 - For more information, see [Variable mapping](#variable-mapping)
175 - cssSpritesheetName `String` - Name to use for spritesheet related variables in preprocessor templates
176 - cssOpts `Object` - Options to pass through to templater
177 - For example `{cssOpts: {functions: false}}` skips output of mixins
178 - See your template's documentation for available options
179 - https://github.com/twolfson/spritesheet-templates#templates
180
181[SASS]: http://sass-lang.com/
182[SCSS]: http://sass-lang.com/
183[sass-maps]: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#maps
184[LESS]: http://lesscss.org/
185[Stylus]: http://learnboost.github.com/stylus/
186[JSON]: http://json.org/
187[handlebars]: http://handlebarsjs.com/
188
189**Returns**:
190- spriteData [`stream.Transform`][transform stream] - Stream that outputs image and CSS as [Vinyl][] objects
191- spriteData.img [`stream.Readable`][readable stream] - Stream for image output as a [Vinyl][] object
192 - `contents` will be a `Stream`
193- spriteData.css [`stream.Readable`][readable stream] - Stream for CSS output as a [Vinyl][] object
194 - `contents` will be a `Buffer`
195
196### Retina parameters
197`gulp.spritesmith` supports retina spritesheet generation via `retinaSrcFilter` and `retinaImgName`. If at least one of these is provided, then we will expect the other and enable retina spritesheet generation.
198
199Repeated parameters have the same properties as above but are repeated for clarity with respect to retina spritesheets.
200
201An example retina spritesheet setup can be found in the [Examples section](#retina-spritesheet).
202
203We receive both normal and retina sprites from the same `gulp.src` so please include them in your original glob. (e.g. `*.png` should include `icon-home.png` and `icon-home@2x.png`).
204
205**We strongly encourage using the `@2x` suffix for retina sprites over `-retina` or `-2x`. There are known ordering issues caused when sharing a `-` delimiter between sprite names and the retina suffix (see [grunt-spritesmith#137][]).**
206
207- params `Object` - Container for `gulp.spritesmith` parameters
208 - retinaSrcFilter `String|String[]` - Filepaths to filter out from incoming stream for our retina spritesheet
209 - This can be a glob as with `src` (e.g. `sprite/*@2x.png`)
210 - The path/glob used should line up with `gulp.src` (e.g. `gulp.src('sprite/*.png')`, `retinaSrcFilter: 'sprite/*@2x.png'`)
211 - For example `sprites/*@2x.png` will filter out `sprite1@2x.png` for a separate retina spritesheet
212 - Under the hood, we will group `sprite1.png` and `sprite1@2x.png` as a group of normal/retina sprites
213 - retinaImgName `String` - Filename to save retina spritesheet as
214 - retinaImgPath `String` - Optional path to use in CSS referring to image location
215 - For example `../sprite@2x.png` will yield CSS with:
216 - `background-image: url(../sprite@2x.png);`
217 - padding `Number` - Padding to place to right and bottom between sprites
218 - By default there is no padding
219 - In retina spritesheets, this number will be doubled to maintain perspective
220 - cssFormat - CSS format to use
221 - By default this is the format inferred by `cssName's` extension
222 - For example `.styl -> stylus_retina`
223 - For more format options, see our formatting library
224 - https://github.com/twolfson/spritesheet-templates#retina-templates
225 - cssVarMap `Function` - Mapping function for each filename to CSS variable
226 - This will run through normal and retina spritesheets
227 - The name used for normal sprites dictates the group name for retina group variables (e.g. `$icon-home` will have group `$icon-home-group`)
228 - For more information, see [Variable mapping](#variable-mapping)
229 - cssRetinaSpritesheetName `String` - Name to use for retina spritesheet related variables in preprocessor templates
230 - cssRetinaGroupsName `String` - Name to use for retina groups related variables in preprocessor templates
231
232**Returns**:
233- spriteData [`stream.Transform`][transform stream] - Stream that outputs image, retina image, and CSS as [Vinyl][] objects
234- spriteData.img [`stream.Readable`][readable stream] - Stream for image outputs (normal and retina) as a [Vinyl][] object
235 - `contents` will be a `Stream`
236- spriteData.css [`stream.Readable`][readable stream] - Stream for retina CSS output as a [Vinyl][] object
237 - `contents` will be a `Buffer`
238
239### Algorithms
240Images can be laid out in different fashions depending on the algorithm. We use [`layout`][] to provide you as many options as possible. At the time of writing, here are your options for `algorithm`:
241
242[`layout`]: https://github.com/twolfson/layout
243
244| `top-down` | `left-right` | `diagonal` | `alt-diagonal` | `binary-tree` |
245|---------------------------|-------------------------------|---------------------------|-----------------------------------|---------------------------------|
246| ![top-down][top-down-img] | ![left-right][left-right-img] | ![diagonal][diagonal-img] | ![alt-diagonal][alt-diagonal-img] | ![binary-tree][binary-tree-img] |
247
248[top-down-img]: https://raw.githubusercontent.com/twolfson/layout/2.0.2/docs/top-down.png
249[left-right-img]: https://raw.githubusercontent.com/twolfson/layout/2.0.2/docs/left-right.png
250[diagonal-img]: https://raw.githubusercontent.com/twolfson/layout/2.0.2/docs/diagonal.png
251[alt-diagonal-img]: https://raw.githubusercontent.com/twolfson/layout/2.0.2/docs/alt-diagonal.png
252[binary-tree-img]: https://raw.githubusercontent.com/twolfson/layout/2.0.2/docs/binary-tree.png
253
254More information can be found in the [`layout`][] documentation:
255
256https://github.com/twolfson/layout
257
258### Templating
259The `cssTemplate` option allows for using a custom template. An example template can be found at:
260
261https://github.com/twolfson/spritesheet-templates/blob/9.3.1/lib/templates/stylus.template.handlebars
262
263The parameters passed into your template are known as `data`. We add some normalized properties via [`spritesheet-templates`][] for your convenience.
264
265- data `Object` Container for parameters
266 - sprites `Object[]` - Array of sprite information
267 - name `String` - Name of the sprite file (sans extension)
268 - x `Number` - Horizontal position of sprite's left edge in spritesheet
269 - y `Number` - Vertical position of sprite's top edge in spritesheet
270 - width `Number` - Width of sprite
271 - height `Number` - Height of sprite
272 - total_width `Number` - Width of entire spritesheet
273 - total_height `Number` - Height of entire spritesheet
274 - image `String` - Relative URL path from CSS to spritesheet
275 - escaped_image `String` - URL encoded `image`
276 - source_image `String` - Path to the original sprite file
277 - offset_x `Number` - Negative value of `x`. Useful to `background-position`
278 - offset_y `Number` - Negative value of `y`. Useful to `background-position`
279 - px `Object` - Container for numeric values including `px`
280 - x `String` - `x` suffixed with `px`
281 - y `String` - `y` suffixed with `px`
282 - width `String` - `width` suffixed with `px`
283 - height `String` - `height` suffixed with `px`
284 - total_width `String` - `total_width` suffixed with `px`
285 - total_height `String` - `total_height` suffixed with `px`
286 - offset_x `String` - `offset_x` suffixed with `px`
287 - offset_y `String` - `offset_y` suffixed with `px`
288 - spritesheet `Object` - Information about spritesheet
289 - width `Number` - Width of entire spritesheet
290 - total_height `Number` - Height of entire spritesheet
291 - image `String` - Relative URL path from CSS to spritesheet
292 - escaped_image `String` - URL encoded `image`
293 - px `Object` - Container for numeric values including `px`
294 - width `String` - `width` suffixed with `px`
295 - height `String` - `height` suffixed with `px`
296 - spritesheet_info `Object` - Container for `spritesheet` metadata and its representation
297 - name `String` - Prefix for spritesheet variables
298 - retina_sprites `Object[]` - Array of retina sprite information
299 - This will only be accessible if we are generating a retina spritesheet
300 - Properties are the same as `sprites` (e.g. `name`, `width`, `source_image`)
301 - retina_spritesheet `Object` - Information about retina spritesheet
302 - This will only be accessible if we are generating a retina spritesheet
303 - Properties are the same as `spritesheet` (e.g. `width`, `px`)
304 - retina_spritesheet_info `Object` - Container for `retina_spritesheet` metadata and its representation
305 - This will only be accessible if we are generating a retina spritesheet
306 - name `String` - Prefix for spritesheet variables
307 - retina_groups `Object[]` - Array of objects that maps to normal and retina sprites
308 - This will only be accessible if we are generating a retina spritesheet
309 - * `Object` - Container for data about sprite mapping
310 - name `String` - Name to refer to mapping by
311 - index `Number` - Index of corresponding normal/retina sprites from `data.sprites`/`data.retina_sprites`
312 - normal `Object` - Normal sprite from `data.sprites` that corresponds to our mapping
313 - This has all the same properties as `data.sprites[*]` (e.g. `name`, `x`, `offset_y`, `px`)
314 - retina `Object` - Retina sprite from `data.retina_sprites` that corresponds to our mapping
315 - This has all the same properties as `data.retina_sprites[*]` (e.g. `name`, `x`, `offset_y`, `px`)
316 - retina_groups_info `Object` - Optional container for metadata about `retina_groups` and its representation
317 - This will only be accessible if we are generating a retina spritesheet
318 - name `String` - Name for `retina_groups`
319 - options `Object` - Options passed in via `cssOpts` in `gulp.spritesmith` config
320
321[`spritesheet-templates`]: https://github.com/twolfson/spritesheet-templates
322
323An example `sprite` is
324
325```js
326{
327 "name": "sprite2",
328 "x": 10,
329 "y": 20,
330 "width": 20,
331 "height": 30,
332 "total_width": 80,
333 "total_height": 100,
334 "image": "nested/dir/spritesheet.png",
335 "escaped_image": "nested/dir/spritesheet.png",
336 "source_image": "path/to/original/sprite.png",
337 "offset_x": -10,
338 "offset_y": -20,
339 "px": {
340 "x": "10px",
341 "y": "20px",
342 "width": "20px",
343 "height": "30px",
344 "total_width": "80px",
345 "total_height": "100px",
346 "offset_x": "-10px",
347 "offset_y": "-20px"
348 }
349}
350```
351
352If you are defining a Handlebars template, then you can inherit from an existing template via [`handlebars-layouts`][] (e.g. `{{#extend "scss"}}`). An example usage can be found in the [Examples section](#handlebars-inheritance).
353
354[`handlebars-layouts`]: https://github.com/shannonmoeller/handlebars-layouts
355
356Example usages can be found as:
357
358- [Handlebars template](#handlebars-template)
359- [Handlebars inheritance](#handlebars-inheritance)
360- [Template function](#template-function)
361
362#### Variable mapping
363The `cssVarMap` option allows customization of the CSS variable names
364
365> If you would like to customize CSS selectors in the `css` template, please see https://github.com/twolfson/spritesheet-templates#css
366
367Your `cssVarMap` should be a function with the signature `function (sprite)`. It will receive the same parameters as `sprites` from [Templating](#templating) except for `escaped_image`, `offset_x`,` offset_y`, and `px`.
368
369```js
370// Prefix all sprite names with `sprite-` (e.g. `home` -> `sprite-home`)
371cssVarMap: function (sprite) {
372 sprite.name = 'sprite_' + sprite.name;
373}
374
375// Generates:
376// $sprite_fork_x = 0px;
377// $sprite_fork_y = 0px;
378
379// As oppposed to default:
380// $fork_x = 0px;
381// $fork_y = 0px;
382```
383
384### Engines
385An engine can greatly improve the speed of your build (e.g. `canvassmith`) or support obscure image formats (e.g. `gmsmith`).
386
387All `spritesmith` engines adhere to a common specification:
388
389https://github.com/twolfson/spritesmith-engine-spec
390
391This repository adheres to specification version: **2.0.0**
392
393Below is a list of known engines with their tradeoffs:
394
395#### pixelsmith
396[`pixelsmith`][] is a `node` based engine that runs on top of [`get-pixels`][] and [`save-pixels`][].
397
398[`pixelsmith`]: https://github.com/twolfson/pixelsmith
399[`get-pixels`]: https://github.com/mikolalysenko/get-pixels
400[`save-pixels`]: https://github.com/mikolalysenko/save-pixels
401
402**Key differences:** Doesn't support uncommon image formats (e.g. `tiff`) and not as fast as a compiled library (e.g. `canvassmith`).
403
404#### phantomjssmith
405[`phantomjssmith`][] is a [phantomjs][] based engine. It was originally built to provide cross-platform compatibility but has since been succeeded by [`pixelsmith`][].
406
407**Requirements:** [phantomjs][] must be installed on your machine and on your `PATH` environment variable. Visit [the phantomjs website][phantomjs] for installation instructions.
408
409**Key differences:** `phantomjs` is cross-platform and supports all image formats.
410
411[`phantomjssmith`]: https://github.com/twolfson/phantomjssmith
412[phantomjs]: http://phantomjs.org/
413
414#### canvassmith
415[`canvassmith`][] is a [node-canvas][] based engine that runs on top of [Cairo][].
416
417**Requirements:** [Cairo][] and [node-gyp][] must be installed on your machine.
418
419Instructions on how to install [Cairo][] are provided in the [node-canvas wiki][].
420
421[node-gyp][] should be installed via `npm`:
422
423```bash
424npm install -g node-gyp
425```
426
427**Key differences:** `canvas` has the best performance (useful for over 100 sprites). However, it is `UNIX` only.
428
429[`canvassmith`]: https://github.com/twolfson/canvassmith
430[node-canvas]: https://github.com/learnboost/node-canvas
431[Cairo]: http://cairographics.org/
432[node-canvas wiki]: (https://github.com/LearnBoost/node-canvas/wiki/_pages
433[node-gyp]: https://github.com/TooTallNate/node-gyp/
434
435#### gmsmith
436[`gmsmith`][] is a [`gm`][] based engine that runs on top of either [Graphics Magick][] or [Image Magick][].
437
438**Requirements:** Either [Graphics Magick][] or [Image Magick][] must be installed on your machine.
439
440For the best results, install from the site rather than through a package manager (e.g. `apt-get`). This avoids potential transparency issues which have been reported.
441
442[Image Magick][] is implicitly discovered. However, you can explicitly use it via `engineOpts`
443
444```js
445{
446 engineOpts: {
447 imagemagick: true
448 }
449}
450```
451
452**Key differences:** `gmsmith` allows for configuring image quality whereas others do not.
453
454[`gmsmith`]: https://github.com/twolfson/gmsmith
455[`gm`]: https://github.com/aheckmann/gm
456[Graphics Magick]: http://www.graphicsmagick.org/
457[Image Magick]: http://imagemagick.org/
458
459## Examples
460### Algorithm
461In this example, we are using the `alt-diagonal` algorithm to guarantee no overlap if images overflow.
462
463**Configuration:**
464
465```js
466{
467 imgName: 'sprite.png',
468 cssName: 'sprite.styl',
469 algorithm: 'alt-diagonal'
470}
471```
472
473**Output:**
474
475![algorithm spritesheet](docs/examples/algorithm/sprite.png)
476
477### Engine
478In this example, we are using the `phantomjssmith` engine as an alternative to the `pixelsmith` default.
479
480**Requirements:**
481
482Install `phantomjssmith` to our `node_modules` via `npm install`.
483
484```bash
485npm install phantomjssmith
486```
487
488Alternatively, we can use `--save` or `--save-dev` to save to our `package.json's dependencies` or `devDependenices`.
489
490```bash
491npm install phantomjssmith --save # Updates {"dependencies": {"phantomjssmith": "1.2.3"}}
492npm install phantomjssmith --save-dev # Updates {"devDependencies": {"phantomjssmith": "1.2.3"}}
493```
494
495**Configuration:**
496
497```js
498// var phantomjssmith = require('phantomjssmith');
499{
500 imgName: 'sprite.png',
501 cssName: 'sprite.styl',
502 engine: phantomjssmith
503}
504```
505
506**Output:**
507
508![engine spritesheet](docs/examples/engine/sprite.png)
509
510### Padding
511The `padding` option allows for inserting spacing between images.
512
513**Configuration:**
514
515```js
516{
517 imgName: 'sprite.png',
518 cssName: 'sprite.styl',
519 padding: 20 // Exaggerated for visibility, normal usage is 1 or 2
520}
521```
522
523**Output:**
524
525![padding spritesheet](docs/examples/padding/sprite.png)
526
527### Retina spritesheet
528In this example, we will use generate a normal and retina spritesheet via the `retinaSrcFilter` and `retinaImgName` parameters.
529
530**Configuration:**
531
532```js
533{
534 // This will filter out `fork@2x.png`, `github@2x.png`, ... for our retina spritesheet
535 // The normal spritesheet will now receive `fork.png`, `github.png`, ...
536 retinaSrcFilter: ['images/*@2x.png'],
537 imgName: 'sprite.png',
538 retinaImgName: 'sprite@2x.png',
539 cssName: 'sprite.styl'
540}
541```
542
543**Normal spritesheet:**
544
545![Normal spritesheet](docs/examples/retina/sprite.png)
546
547**Retina spritesheet:**
548
549![Retina spritesheet](docs/examples/retina/sprite@2x.png)
550
551### Handlebars template
552In this example, we will use `cssTemplate` with a `handlebars` template to generate CSS that uses `:before` selectors.
553
554**Template:**
555
556```handlebars
557{{#sprites}}
558.icon-{{name}}:before {
559 display: block;
560 background-image: url({{{escaped_image}}});
561 background-position: {{px.offset_x}} {{px.offset_y}};
562 width: {{px.width}};
563 height: {{px.height}};
564}
565{{/sprites}}
566```
567
568**Configuration:**
569
570```js
571{
572 imgName: 'sprite.png',
573 cssName: 'sprite.css',
574 cssTemplate: 'handlebarsStr.css.handlebars'
575}
576```
577
578**Output:**
579
580```css
581.icon-fork:before {
582 display: block;
583 background-image: url(sprite.png);
584 background-position: 0px 0px;
585 width: 32px;
586 height: 32px;
587}
588.icon-github:before {
589/* ... */
590```
591
592### Handlebars inheritance
593In this example, we will extend the SCSS template to provide minimal variables. The JSON at the front comes from the original template and is required to provide consistent casing and default options.
594
595Different block sections for each template are documented in:
596
597https://github.com/twolfson/spritesheet-templates
598
599**Template:**
600
601```handlebars
602{
603 // Default options
604 'functions': true,
605 'variableNameTransforms': ['dasherize']
606}
607
608{{#extend "scss"}}
609{{#content "sprites"}}
610{{#each sprites}}
611${{strings.name}}: ({{px.x}}, {{px.y}}, {{px.offset_x}}, {{px.offset_y}}, {{px.width}}, {{px.height}}, {{px.total_width}}, {{px.total_height}}, '{{{escaped_image}}}', '{{name}}', );
612{{/each}}
613{{/content}}
614{{#content "spritesheet"}}
615${{spritesheet_info.strings.name_sprites}}: ({{#each sprites}}${{strings.name}}, {{/each}});
616${{spritesheet_info.strings.name}}: ({{spritesheet.px.width}}, {{spritesheet.px.height}}, '{{{spritesheet.escaped_image}}}', ${{spritesheet_info.strings.name_sprites}}, );
617{{/content}}
618{{/extend}}
619```
620
621**Configuration:**
622
623```js
624{
625 imgName: 'sprite.png',
626 cssName: 'sprite.scss',
627 cssTemplate: 'handlebarsInheritance.scss.handlebars'
628}
629```
630
631**Output:**
632
633```scss
634$fork: (0px, 0px, 0px, 0px, 32px, 32px, 64px, 64px, 'sprite.png', 'fork', );
635$github: (32px, 0px, -32px, 0px, 32px, 32px, 64px, 64px, 'sprite.png', 'github', );
636$twitter: (0px, 32px, 0px, -32px, 32px, 32px, 64px, 64px, 'sprite.png', 'twitter', );
637$spritesheet-sprites: ($fork, $github, $twitter, );
638$spritesheet: (64px, 64px, 'sprite.png', $spritesheet-sprites, );
639/* ... */
640```
641
642### Template function
643In this example, we will use `cssTemplate` with a custom function that generates YAML.
644
645**Configuration:**
646
647```js
648// var yaml = require('js-yaml');
649{
650 imgName: 'sprite.png',
651 cssName: 'sprite.yml',
652 cssTemplate: function (data) {
653 // Convert sprites from an array into an object
654 var spriteObj = {};
655 data.sprites.forEach(function (sprite) {
656 // Grab the name and store the sprite under it
657 var name = sprite.name;
658 spriteObj[name] = sprite;
659
660 // Delete the name from the sprite
661 delete sprite.name;
662 });
663
664 // Return stringified spriteObj
665 return yaml.safeDump(spriteObj);
666 }
667}
668```
669
670**Output:**
671
672```yaml
673fork:
674 x: 0
675 "y": 0
676 width: 32
677 height: 32
678 source_image: /home/todd/github/gulp.spritesmith/docs/images/fork.png
679 image: sprite.png
680 total_width: 64
681 total_height: 64
682 escaped_image: sprite.png
683 offset_x: -0.0
684 offset_y: -0.0
685 px:
686 x: 0px
687 "y": 0px
688 offset_x: 0px
689 offset_y: 0px
690 height: 32px
691 width: 32px
692 total_height: 64px
693 total_width: 64px
694github:
695# ...
696```
697
698## Contributing
699In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint via `npm run lint` and test via `npm test`.
700
701## Attribution
702GitHub and Twitter icons were taken from [Alex Peattie's JustVector Social Icons][justvector].
703
704Fork designed by [P.J. Onori][onori] from The Noun Project.
705
706[justvector]: http://alexpeattie.com/projects/justvector_icons/
707[noun-fork-icon]: http://thenounproject.com/noun/fork/#icon-No2813
708[onori]: http://thenounproject.com/somerandomdude
709
710## Unlicense
711As of Feb 09 2014, Todd Wolfson has released this repository and its contents to the public domain.
712
713It has been released under the [UNLICENSE][].
714
715[UNLICENSE]: UNLICENSE