Coder Social home page Coder Social logo

atlaspack's Introduction

atlaspack

Pack rectangles (or images) into a rectangle (or canvas texture atlas). View the demo.

example

This will load 0-99 images and fit them onto a canvas texture atlas:

// create a canvas
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = 128;
canvas.height = 128;

// Create a starting atlas based on the canvas
var atlas = require('atlaspack')(canvas);

for (var i = 0; i < 100; i++) {
  var img = new Image();
  img.id = i;
  img.src = 'images/' + i + '.png';
  img.onload = function() {
    atlas.pack(img);
  };
}

You can pack generic rectangles into an atlas as well. The following example will create a 512x512 atlas and load random shapes into document.body every second:

// Specify a width and height of the starting atlas
var atlas = require('atlaspack')(512, 512);

(function loop() {
  var width  = Math.random() * 32;
  var height = Math.random() * 32;

  var node = atlas.pack({width: width, height: height});

  var div = document.createElement('div');
  div.style.position = 'absolute';
  div.style.width  = width + 'px';
  div.style.height = height + 'px';
  div.style.left   = node.rect.x + 'px';
  div.style.top    = node.rect.y + 'px';
  document.body.appendChild(div);

  setTimeout(loop, 1000);
}());

api

atlaspack([...])

Takes either 1 canvas argument, 2 width, height arguments or 4 x, y, width, height arguments. Returns an instance of Atlas.

atlaspack.Atlas([...])

Takes either 1 canvas argument, 2 width, height arguments or 4 x, y, width, height arguments.

atlas.pack(rect || image || object)

Recursively tries to pack rect (or image, object) into the atlas. Will return false if fails to fit the rect otherwise will return the atlas node the rect has been packed into:

var Atlas = require('atlaspack').Atlas;
var Rect = require('atlaspack').Rect;

var atlas = new Atlas(128, 128), node;

node = atlas.pack(new Rect(0, 0, 32, 32));
node = atlas.pack({x: 0, y: 0, w: 32, h: 32});

var img = new Image();
img.src = 'myimage.png';
img.onload = function() {
  node = atlas.pack(img);
};

atlas.expand(rect || img || object)

Will recursively expand the atlas to fit a new rect then pack the rect into the expanded atlas. Returns the newly expanded atlas:

var atlas = require('atlaspack')(128, 128);
var dontfit = {x: 0, y: 0, w: 256, h: 256};
var node = atlas.pack(dontfit);
if (node === false) {
  atlas = atlas.expand(dontfit);
}

atlas.index()

Returns a flat array of rects which have images within the atlas. Useful for retrieving an atlas key:

var atlas = require('atlaspack')(128, 128);

function done() {
  atlas.index().forEach(function(rect) {
    console.log('Name: ' + rect.name);
    console.log('Coords: ' + rect.x + ', ' + rect.y);
  });
}

for (var i = 0; i < 100; i++) {
  var img = new Image();
  img.src = 'images/' + i + '.png';

  // Will use the id || name || src of the image as the rect.name
  img.id = i;

  img.onload = function() {
    atlas.pack(img);
    if (i === 99) done();
  };
}

atlas.uv([width, height])

Returns an object with rect names as keys containing an array of UV mapping coordinates between 0-1 with TRBL:

var uvmap = atlas.uv();
/* {
              TOP   RIGHT  BOTTOM  LEFT
  'name':  [ [0,0], [1,0], [1,1], [0,1] ],
} */

Specify a width and height to override the dimensions the UVs will calculate from. Otherwise it will use the atlas.rect width and height.

atlas.json([input])

Exports or imports a JSON key for the ability to save the atlas state and restore it:

var jsonkey = atlas.json();
// then later
atlas = atlas.json(jsonkey);

// make sure to set your canvas if using a canvas too
atlas.canvas = mycanvas;

atlas.tilepad

Set this boolean property to true if you would like each packed image to pad itself with a tiled pattern of itself. Useful for avoiding texture bleeding when mipmapping.

atlaspack.Rect(x, y, w, h)

Creates a rectangle instance.

rect.fitsIn(rect)

Returns a boolean whether a rect fits within another rect.

rect.sameSizeAs(rect)

Returns a boolean whether a rect is the same size as another rect.

install

With npm do:

npm install atlaspack

using standalone / non-browserify

It is wrapped in an UMD for use outside of browserify.

Add a script tag to your HTML and use globally exposed atlaspack variable:

<script src="node_modules/atlaspack/index.js"></script>
<script>
var atlas = window.atlaspack(canvas);
</script>

release history

  • 1.0.0 - Allow canvas elements to be packed too.
  • 0.2.7 - Wrap in UMD for use outside of commonjs loaders.
  • 0.2.6 - Fix _uvcache should be an object (@deathcap).
  • 0.2.5 - clearRect before placing image onto a canvas.
  • 0.2.4 - Add width/height overrides to uv method.
  • 0.2.3 - Add tilepad property to help with mipmapping.
  • 0.2.2 - Ability to get and set JSON key.
  • 0.2.1 - Add uv method for uv coordinates.
  • 0.2.0 - Add expand and index methods.
  • 0.1.0 - initial release

license

Copyright (c) 2016 Kyle Robinson Young
Licensed under the MIT license.

atlaspack's People

Contributors

deathcap avatar rymohr avatar shama 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

Watchers

 avatar  avatar  avatar  avatar

atlaspack's Issues

Invalid packing for long rectangles

I tried to pack every 3 words from lorem ipsum and run into weird layout issue:

screen shot 2017-11-21 at 17 30 52

Despite lots of white space on the left i failed to pack 2 short sentences:
screen shot 2017-11-21 at 17 32 34

Tried same rects with the original binpack with the same result

screen shot 2017-11-21 at 17 38 41

Data i'm using

[{"width":175.625,"height":30},{"width":194.521484375,"height":30},{"width":201.19140625,"height":30},{"width":202.333984375,"height":30},{"width":187.8515625,"height":30},{"width":166.7578125,"height":30},{"width":152.275390625,"height":30},{"width":127.841796875,"height":30},{"width":182.32421875,"height":30},{"width":114.4921875,"height":30},{"width":201.181640625,"height":30},{"width":120.048828125,"height":30},{"width":253.4375,"height":30},{"width":166.71875,"height":30},{"width":143.3984375,"height":30},{"width":153.388671875,"height":30},{"width":210.1171875,"height":30},{"width":282.3828125,"height":30},{"width":170.078125,"height":30},{"width":177.861328125,"height":30},{"width":106.708984375,"height":30},{"width":196.77734375,"height":30},{"width":163.41796875,"height":30},{"width":197.87109375,"height":30},{"width":173.427734375,"height":30},{"width":170.087890625,"height":30},{"width":177.861328125,"height":30},{"width":154.53125,"height":30},{"width":253.4375,"height":30},{"width":214.53125,"height":30},{"width":132.28515625,"height":30},{"width":146.728515625,"height":30}]

Have you ever encountered any issues like that?

index() does not work with rects or literals

If I pack a rect or a literal, I can't find it again using index.

var atlaspack = require('atlaspack');
var Rect = atlaspack.Rect;

var atlas = atlaspack(100, 100);

var rect = new Rect(0, 0, 10, 10);
rect.name = "from a rect";
atlas.pack(rect);

atlas.pack({x:0, y:0, w:10, h:10, name:"literal"});

console.log(atlas.index()); // []
console.log(atlas.uv()); // {}

When I use pack() I can fix it manually by doing packed = pack(...); packed.rect.name = "somename" but I can't do that if I use expand().

Introduce TypeScript version

Hi @shama. Thank you for sharing this great library.

I've rewritten atlaspack in TypeScript link because of my opinionated passion for type safety :) Just wanted to let you know how your code looks like in TypeScript.

By the way, I've learned a lot from your code around voxel.js world. Thank you for your contribution again!

Move umd build to dist/atlaspack.js

With ES6 adoption growing fast it's nice to have the original source. The current approach results in errors like the following in webpack:

WARNING in ~/atlaspack/index.js
Critical dependencies:
1:440-447 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
@ ~/atlaspack/index.js 1:440-447

May I suggest moving the umd build to dist/atlaspack.js instead?

Related to #8

improve uv docs

currently the docs for atlas.uv() state:

var uvmap = atlas.uv();
/* {
              TOP   RIGHT  BOTTOM  LEFT
  'name':  [ [0,0], [1,0], [1,1], [0,1] ],
} */

When I think of a quad, I think of four pairs of points, so instead of TOP, RIGHT, BOTTOM, and LEFT, I would expect something more like TOP-LEFT, TOP-RIGHT, BOTTOM-LEFT, BOTTOM-RIGHT.

Add index method

Returns a flat array of rect positions for an index. Also add name to Rect and read id || name from images to set.

this._uvcache is an array but used as an object?

Noticed this while debugging.. atlas.uv() appeared to return an empty array [], even though it had properties set for each of the textures (as expected). pack() sets _uvcache to an empty array:

this._uvcache = [];

although earlier in the Atlas constructor it is set to a new object:

this._uvcache = Object.create(null);

uv() uses the .length property, presumably intending an array:

if (self._uvcache.length > 0) {
  return self._uvcache;
}

but the same function sets self._uvcache[atlas.rect.name].

Should _uvcache really be an array? This could potentially cause problems with texture names clashing with Array properties:

screen shot 2014-06-08 at 3 54 00 pm

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.