There are two ways how to set resolution of atlas (image) :

- naming atlas file with respective @1x (or @2x, etc) suffix
- let TexturePacker do the job and PIXI.Loader will respect atlas scale defined in meta part of json file

First case will have priority over the second one. That means whatever scale is defined in json file it will be ignored as long as resolution suffix is appended to file name. Meta scale will be used in case resolution suffix is not present in file name.

Sometimes, second case can give us little troubles.

If we have file named just 'atlas.json' without resolution suffix in file name and meta part of this file will look similar to following (notice scale and it's value of 0.5) :

"meta": {
	"app": "http://www.codeandweb.com/texturepacker",
	"version": "1.0",
	"image": "atlas.png",
	"format": "RGBA8888",
	"size": {"w":64,"h":64},
	"scale": "0.5"
}

Result of that will be that textures created from this atlas will be displayed at 200% of their actual size. Which is also desired behaviour when working with different render resolutions, but for now we want to suppress that behaviour and we want to display textures at their original size - as if they were made for pixel ratio 1.

Maybe you can't rename the file for some reason or you are moving from Pixi v3 to Pixi v4 and you are too lazy to rename all the files in existing project.

Luckily we can use 'pre' method of resource loader, which will run our code before resource is loaded. We will modify meta part at the point when json file is loaded and before texture with given resolution is created.

Here is full source code :

var app;

window.onload = function()
{
	app = new PIXI.Application(200, 200, { backgroundColor:0x202060 });
	
	document.body.appendChild(app.view);

	var loader = new PIXI.loaders.Loader();
	
	loader.pre(preResource);
	
	loader.add('myAtlas', 'images/atlas.json');
	loader.once('complete', onAssetsLoaded);

	loader.load();
};

function onAssetsLoaded()
{
	var texture = PIXI.Texture.fromFrame('something.png');
	var sprite = new PIXI.Sprite(texture);
	
	app.stage.addChild(sprite);
}

function preResource(resource, next)
{
	if (resource.loadType === PIXI.loaders.Resource.TYPE.JSON)
	{
		resource.onComplete.once(function(res) 
		{
			if (res.data && res.data.meta)
			{
				res.data.meta.scale = "1";
			}			
		});
	}
	
	next();
};
SEE IT IN ACTION

And compare the result with original code, which isn't using 'preResource' method (image is scaled up twice, because json meta part tells Pixi to use scale 0.5).

SEE THE ORIGINAL

Newsletter

Subscribe to receive our latest posts and tutorials. No spam, unsubscribe at any time.

Keep in Touch

Want to ask something, have an idea for improvement or just want say hello? Then feel free to contact us