Skip to content

Instantly share code, notes, and snippets.

@danielberndt
Last active February 26, 2020 12:36
Show Gist options
  • Save danielberndt/98dd90adb1a623fc93e3a7d7daafd675 to your computer and use it in GitHub Desktop.
Save danielberndt/98dd90adb1a623fc93e3a7d7daafd675 to your computer and use it in GitHub Desktop.
load pixi.js sprite sheet jsons via webpack
`
this allows you to use all of webpack's goodness to load your sprites.
here's some benefits:
- saving one roundtrip since webpack's json-loader will inline the json data into the script. Thus it doesn't need to be loaded from the server first
- use a lot of the file-loader power and beyond to create cache-busting urls, and apply image-minification via e.g. image-webpack-loader
`
import PIXI from "pixi.js";
export default function loadFromJson(name, pathToImage, data, resolution = parseInt(data.meta.scale, 10)) {
PIXI.loader.add(name, pathToImage, res => {
// code mostly taken from here: https://github.com/pixijs/pixi.js/blob/039200b46d7840f065faa50739e4b98f69678db4/src/loaders/spritesheetParser.js
const frames = data.frames;
const frameKeys = Object.keys(frames);
let frameIndex = 0;
while (frameIndex < frameKeys.length) {
const frame = frames[frameKeys[frameIndex]];
const rect = frame.frame;
if (rect) {
let size = null;
let trim = null;
if (frame.rotated) {
size = new PIXI.Rectangle(rect.x, rect.y, rect.h, rect.w);
} else {
size = new PIXI.Rectangle(rect.x, rect.y, rect.w, rect.h);
}
// Check to see if the sprite is trimmed
if (frame.trimmed) {
trim = new PIXI.Rectangle(
frame.spriteSourceSize.x / resolution,
frame.spriteSourceSize.y / resolution,
frame.sourceSize.w / resolution,
frame.sourceSize.h / resolution
);
}
// flip the width and height!
if (frame.rotated) {
const temp = size.width;
size.width = size.height;
size.height = temp;
}
size.x /= resolution;
size.y /= resolution;
size.width /= resolution;
size.height /= resolution;
PIXI.utils.TextureCache[frameKeys[frameIndex]] = new PIXI.Texture(res.texture.baseTexture, size, size.clone(), trim, frame.rotated);
}
frameIndex++;
}
});
}
import loadFromJson from "./load-from-json";
loadFromJson("bunny_walk", require("./sprites/bunny_walk.png"), require("./sprites/bunny_walk.json"));
PIXI.loader.once("complete", () => {
// ... do your stuff as usual
})
@shshaw
Copy link

shshaw commented Sep 2, 2016

Added an issue on PIXI's repo to build this functionality in: pixijs/pixijs#2906

@danielberndt
Copy link
Author

Ah lovely! Thanks for sharing :)

@xiaer93
Copy link

xiaer93 commented Jun 8, 2018

Thanks for sharing :),This is really useful to solve my problem~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment