October 26, 2014

JavaScript: Use two.js to prepare svg shapes for a PIXI.js Sprite

When creating PIXI.js Sprites from vector SVG shapes, you may want to scale up the SVG before turning it into a bitmap sprite, in order to get the best resolution for your screen. Here's a little snippet that will create a two.js canvas to do just that, and return a PIXI.Sprite with your ideal bitmap size:
// init Two for svg import
Two.Resolution = 24;
var _twoCanvas = new Two({
  width: 400,
  height: 400,
  type: Two.Types.canvas
});

// create method to read an svg element from the DOM, scale it, and return a PIXI.Sprite
var getScaledSpriteFromSVG = function(elemId, scale) {
  _twoCanvas.clear();

  // import svg from DOM, scale up, fit canvas to svg and render!
  var shape = _twoCanvas.interpret(document.getElementById(elemId));
  shape.scale = scale;
  var charH = Math.ceil(shape.getBoundingClientRect().height);
  var charW = Math.ceil(shape.getBoundingClientRect().width);
  _twoCanvas.width = charW;
  _twoCanvas.height = charH;
  _twoCanvas.update();

  // grab two.js canvas contents by exporting its base64 png content
  var newSvgSprite = new PIXI.Sprite(PIXI.Texture.fromImage(_twoCanvas.renderer.domElement.toDataURL()));
  newSvgSprite.anchor.x = 0.5;
  newSvgSprite.anchor.y = 0.5;

  return newSvgSprite;
};

var birdieSvgSprite = getScaledSpriteFromSVG('birdie', 2);
And this should be in your DOM, which could be hidden via css (display:none;):
<svg id="birdie">-svg content here-</svg>

No comments:

Post a Comment