Coder Social home page Coder Social logo

spritesheet.js's Introduction

spritesheet.js

Spritesheet.js is command-line spritesheet (a.k.a. Texture Atlas) generator written in node.js.

Supported spritesheet formats

  • Starling / Sparrow
  • JSON (i.e. PIXI.js)
  • Easel.js
  • cocos2d (i.e. version 2.x)
  • cocos2d-v3 (i.e. version 3.x)
  • CSS (new!)

Usage

Command Line

$ spritesheet-js assets/*.png

Options:

$ spritesheet-js
Usage: spritesheet-js [options] <files>

Options:
-f, --format  format of spritesheet (starling, sparrow, json, pixi.js, easel.js, cocos2d)                                                          [default: "json"]
-n, --name    name of generated spritesheet                                                                                                        [default: "spritesheet"]
-p, --path    path to export directory                                                                                                             [default: "."]
--fullpath    include path in file name                                                                                                            [default: false]
--prefix      prefix for image paths (css format only)                                                                                             [default: ""]
--trim        removes transparent whitespaces around images                                                                                        [default: false]
--square      texture should be s square                                                                                                           [default: false]
--powerOfTwo  texture width and height should be power of two                                                                                      [default: false]
--validate    check algorithm returned data                                                                                                        [default: false]
--algorithm   packing algorithm: growing-binpacking (default), binpacking (requires passing --width and --height options), vertical or horizontal  [default: "growing-binpacking"]
--width       width for binpacking                                                                                                                 [default: undefined]
--height      height for binpacking                                                                                                                [default: undefined]
--padding     padding between images in spritesheet                                                                                                [default: 0]
--scale       percentage scale                                                                                                                     [default: "100%"]
--fuzz        percentage fuzz factor (usually value of 1% is a good choice)                                                                        [default: ""]

Node.js

var spritesheet = require('spritesheet-js');

spritesheet('assets/*.png', {format: 'json'}, function (err) {
if (err) throw err;

console.log('spritesheet successfully generated');
});

Trimming / Cropping

Spritesheet.js can remove transparent whitespace around images. Thanks to that you can pack more assets into one spritesheet and it makes rendering a little bit faster.

NOTE: Some libraries such as Easel.js dont't support this feature. Trimming / Cropping

Installation

  1. Install ImageMagick
    • On versions 7.x and higher you must install the optional Legacy Tools
  2. npm install spritesheet-js -g

Test

mocha test

Thanks Przemysław Piekarski for logo design and assets in examples.

spritesheet.js's People

Contributors

akinoniku avatar arjanfrans avatar endel avatar flouthoc avatar freshly-pressed-trousers avatar getkey avatar gprzybylowicz avatar jotson avatar krzysztof-o avatar kyuur avatar matthijsgroen avatar mems avatar mildfuzz avatar mpazik avatar naranjamecanica avatar neonaleon avatar rblopes avatar serprex avatar smoke avatar thristhart avatar tzet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spritesheet.js's Issues

Pattern option didn't work from command line

From command line on Windows - for me *.png (or any other pattern) didn't work, I had to paste the files one by one to the command line. It seemed to use only 1 file file and the image output was broken(showing part of that one image). I tracked this down to this line:

generate(argv._, argv, function (err) {

And specifically, inside that function, this line:

files = Array.isArray(files) ? files : glob.sync(files);

For me argv._ was always treated as array, which caused glob.sync to never execute. Had to do this in the main js file (updated):

...
  var args;
  if (argv._.length == 1) {
  	args = argv._[0];
  } else {
	args = argv._;
  }
  generate(args, argv, function (err) {
...

Now it's working fine.

shelljs breaks on windows

Hi, after the pull request at #43 was accepted spritesheet-js is no longer working on Windows when specifying a long list of files as shelljs doesn't handle the Windows argument length limit for exec() like platform-cmd did...

Can we get that functionality back by maybe just including the platform-cmd code for exec() that worked?

Thanks in Advance

Lots of files can cause argument list too long exceptions on child process exec

Hi I've been using the lib for a while and it's an absolute joy to use - especially when compared to how I've handled asset management before!

I've come across an issue as I've used it at scale though - for a very large spritesheet in my case including 1k+ individual files which all typically tiny 16x16 sprites I'm getting an argument list too long exception from the imagemagick exec as the length of the imagemagick command resulting from the thousands of chained image paths & composite commands is over the buffer length allowed by a terminal command.

I've forked the repo locally and have a change that fixes it - by batching the transformation calls to imagemagick on top of each other, I'm happy to raise if someone can PR but unsure of if this project is actively maintained?

wrong result with powerOfTwo option

Given the following 4 pictures:

claw1

claw2

claw3

claw1

The end result with powerOfTwo option misses one frame (and the image size is not actually power of two):

result

Ignore duplicated assets

Hey there,

Would be nice to re-use duplicated assets when necessary. I plan to implement this feature soon if you're interested.

Cheers!

variable in the image's source isn't allowed?

When I try to add a variable to the files parameter or add a query string to it, it gives me the error that no files have been specified. For example, using uuid inside of the files path wouldn't work.

// doesn't work
    var UUID = uuidv4()
    var UUIDPATH = `server/assets/${UUID}/*.jpeg`
spritesheet(UUIDPATH, {format: 'json', path: 'server/assets/test/'}, function (err) {
      if (err) throw err;
      console.log('spritesheet successfully generated');
    });
// doesn't work
    var UUID = uuidv4()
spritesheet(`server/assets/${UUID}/*.jpeg`, {format: 'json', path: 'server/assets/test/'}, function (err) {
      if (err) throw err;
      console.log('spritesheet successfully generated');
    });

//doesn't work
    var UUID = uuidv4()
spritesheet('server/assets/'+UUID+'/*.jpeg', {format: 'json', path: 'server/assets/test/'}, function (err) {
      if (err) throw err;
      console.log('spritesheet successfully generated');
    });

ImageMagick Installation Issue

I tried to install ImageMagick version 6 and 7 (not simultaneously) and tried to run in both of nodejs and command line but I still face the same issue (image below). Any help, pls?
imagemagick_issue

Unable to find files even though they're right there :-)

Steps to repo

  1. Directory structure is
v1 / fly1_0.png
v1 / fly1_2.png 
...
v1 / fly1_5.png
  1. Install locally yarn --dev spritesheet-js
  2. Run yarn spritesheet-js -f json v1/*.png

Result:

Error: Command failed: identify "/Users/uri/v1/fly1_0.png" "/Users/uri/v1/fly1_1.png" "/Users/uri/v1/fly1_2.png" "/Users/uri/v1/fly1_3.png" "/Users/uri/v1/fly1_4.png" "/Users/uri/v1/fly1_5.png"

Note: the above path is incorrect!

Environment:

  • macosx high sierra
  • node 16.13.1
  • yarn 1.22.17
  • latest spritesheet-js

Is it possible to specify padding?

Sprites in the spritesheets are showing a few pixels from neighbouring images. Is it possible to add padding around the sprites in the sheet?

Automatic Parsing of animations frames

I have begun work on automatically parsing animations sequences to group them together for easel.js (may be of benefit to other frameworks, I don't know). You can see where I have got to here

The problem it currently has is that when the animation frames are trimmed, their registration point moves. This makes it very hard to line up the animation frames for use.

One idea I have had is that animation frames are identified earlier on, and only have their bottom and right edges trimmed. This would keep 0,0 in the same place for each frame. Something like this should do it:

exports.trimSouthEast = function(file, i){
    /*
     * Trims the bottom and right edges
     */

        var origFile = process.cwd() + "/" + file;
        origFile = origFile.replace(/\s/g, '\ ');
        var tempFile1 = os.tmpDir() + 'image1_' +i+'.png';
        var tempFile2 = os.tmpDir() + 'image2_' +i+'.png';

        var args1 = " -gravity North -background white -splice 0x1  -background black -splice 0x1 -trim  +repage -chop 0x1 ";
        var args2 = " -gravity West -background white -splice 1x0  -background black -splice 1x0 -trim  +repage -chop 1x0 ";


        exec("convert " + origFile + args1 + tempFile1, function() {
            exec("convert " + tempFile1 + args2 + tempFile2, function(){
                fs.rename(tempFile2, origFile, function(err){
                    if (err) {
                        console.error("I couldn't process file", origFile);
                        console.log(err);
                    }
                });

            });
        });


};

error running cli

Error: Command failed: /bin/sh: 1: identify: not found
spritesheet-js version 0.7.2
OS: Ubuntu 14.04

Filesizes are larger than they could be

I have a set of roughly 80 sprites. When I run spritesheet followed by pngcrush:

spritesheet-js --trim -f easel.js *.png pngcrush -ow -reduce -brute spritesheet.png

I end up with a 1.9mb file. When I use imagemagick manually:

convert -append -background none *.png spritesheet.png pngcrush -ow -reduce -brute spritesheet.png

I end up with a 1.1mb file.

From what I can tell, spritesheet-js is using imagemagick so such a huge difference baffles me.

The spritesheet-js file is 763 × 8,196 (6,253,548px) where as the manual spritesheet is 600 × 54,064 (32,438,400px). That's a huge difference in physical size, but the file difference is totally on it's head!

Any ideas how I can fix this?

Error generator.js line 47

C:\Users\MYUSER\AppData\Roaming\npm\node_modules\spritesheet-js\lib\generator.js:4
7
files[i].width = parseInt(size[1], 10);
^
TypeError: Cannot set property 'width' of undefined

node.js v0.10.25
imagemagik ImageMagick-6.8.8-6-Q16-x64-dll.exe

wrong file encoding for index.js

there are some problems with the encoding of the index.js file.

To make it work on linux I had to copy the content of index.js, remove index.js and recreate the file from scratch. After that everything's working correctly.

json generated by the spritesheets not updating

Hello!

I'm creating a spritesheet and its accompanying json with this in my nodejs file
function createSpriteSheet(source, dest, spriteSheetName, pad) {

    try {
        var stats = fs.statSync(source);
        if (stats.isDirectory())    source = source + "/*";
        } catch (err) {
        return console.error("spritesheet error : " + err);
    }
    return new Promise(function(resolve, reject){
        spritesheet(source, {format: 'json', path: dest, name: spriteSheetName, padding: pad}, function (err) {
            if (err)    reject(err);
            resolve('ok');
        });
    });
}

However, while the spritesheet image is being updated with the latest images, the json isn't. But it gets updated if I restart npm server.

Someone please resolve this as soon as possible.

Can't put sprites in order

For some reason mine just refuses to put my spritesheet together in numerical order. It tries but has a few bugs in how it orders numbers.

For example... with files labeled 00 - 41 it will output them 00, 21, 02, 03, instead of 00, 01, 02, 03

"Unhandled 'error' event" when testing with example sprite sheet

When trying to run and create sprite sheets, there is an error. Have tested using the provided examples, and copying commands from the instructions. Copy and pasted from Terminal:

pm run spritesheet
Projmate v0.0.9 /usr/local/lib/node_modules/projmate-cli/node_modules/projmate-core
pm-run env: development file: ./Projfile.coffee
spritesheet ==> spritesheet.development

events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:980:11)
at Process.ChildProcess._handle.onexit (child_process.js:771:34)
jacks-mbp-2:example JackWild$

state of project ?

Hi,

Could you tell us if the project is still alive ?
I saw pull requests ready to be merged 2 or 3 years old, and some are waiting for changes (like extrude)
Do you plan to continue the project ?
Should the community do a hard fork to keep it alive ?
Thanks for your answers,

An avid user :)

cocos2d-x template is not working correctly

Here is a patched version of the template that works for me:

{{=<% %>=}}

frames <%#files%> <%#trimmed%> <%name%><%extension%> frame {{<%x%>,<%y%>},{<%width%>,<%height%>}} offset {<%trim.offsetX%>,<%trim.offsetY%>} rotated sourceColorRect {{<%trim.x%>,<%trim.y%>},{<%trim.width%>,<%trim.height%>}} sourceSize {<%trim.width%>,<%trim.height%>} <%/trimmed%> <%^trimmed%> <%name%><%extension%> frame {{<%x%>,<%y%>},{<%width%>,<%height%>}} offset {0,0} rotated sourceColorRect {{0,0},{<%width%>,<%height%>}} sourceSize {<%width%>,<%height%>} <%/trimmed%> <%/files%> metadata format 2 realTextureFileName <%name%>.png size {<%width%>,<%height%>} textureFileName <%name%>.png

Is there a way to preserve the order of the frames in the generated .json files based on the order passed to the tool?

Hi @krzysztof-o, great work on this package! I really love it!

As for the question - if there is no way, would you consider adding such option or at least sort the frames with Natural sorting?

The JSON below is what I get, but I would like to have bees/00001.png, bees/00002.png, etc. - just the way I have passed the files, using ls bees/* | sort -V

{
    "meta": {
        "image": "bees.png",
        "size": {"w":512,"h":256},
        "scale": "1"
    },
    "frames": {
        "bees/00003.png":
        {
            "frame": {"x":166,"y":95,"w":166,"h":95},
            "rotated": false,
            "trimmed": false,
            "spriteSourceSize": {"x":0,"y":0,"w":166,"h":95},
            "sourceSize": {"w":166,"h":95}
        },
        "bees/00002.png":
        {
            "frame": {"x":0,"y":95,"w":166,"h":95},
            "rotated": false,
            "trimmed": false,
            "spriteSourceSize": {"x":0,"y":0,"w":166,"h":95},
            "sourceSize": {"w":166,"h":95}
        },
        "bees/00001.png":
        {
            "frame": {"x":166,"y":0,"w":166,"h":95},
            "rotated": false,
            "trimmed": false,
            "spriteSourceSize": {"x":0,"y":0,"w":166,"h":95},
            "sourceSize": {"w":166,"h":95}
        },
        "bees/00000.png":
        {
            "frame": {"x":0,"y":0,"w":166,"h":95},
            "rotated": false,
            "trimmed": false,
            "spriteSourceSize": {"x":0,"y":0,"w":166,"h":95},
            "sourceSize": {"w":166,"h":95}
        }
    }
}

Scale not working

I run spritesheet-js --scale 50% [my files] and not scaling is applied.

For any value of scale that i provide, the resulting spritesheet.png and spritesheet.json are the same size.

spritesheet-js version 1.2.6

Uncaught exception on Windows

When running spritesheet.js on Windows I always get the following message:

> spritesheet-js -f json *.png                                                
                                                                              
C:\Users\SomeUser\AppData\Roaming\npm\node_modules\spritesheet-js\index.js:129     
    if (err) throw err;                                                       
             ^                                                                
1                                                                             

I tried lots of different parameters with the same result. spritesheet-js -h works fine. I install spritesheet.js via npm.

Some basic system info:

System: Windows 7 64-bit
spritesheet.js version: 1.2.6
node.js version: 6.10.0
npm version: 3.10.10

Running from command line skipping first png in set

I have a set of 20 png's to add to a spritesheet.

Running spritesheet-js -f easel.js --trim *.png create a sheet and json document as expected, but does not add the first image in the set (listed alphabetically).

It is repeatable in that renaming the first image causes a different image to be skipped.

For now I have added a superfluous image 1.png which is accounting for the error, but would be good to be fixed

Weird offset on transparent image with trim.

including a completely transparent image and using the trim option results in this:

"space.png":
               {
                        "frame": {"x":182,"y":18,"w":1,"h":1},
                        "rotated": false,
                        "trimmed": true,
                        "spriteSourceSize": {"x":4294967294,"y":4294967294,"w":1,"h":1},
                        "sourceSize": {"w":9,"h":34}
                },

note the x/y of spriteSourceSize.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.