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) {

  // 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;

  // 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>

JavaScript: Automatically scroll to the end of an infinitely-scrolling page

Simply paste this code into your browser console:
var scrollInterval = setInterval(function(){window.scrollTo(0,-999999999999)},500)
When it's done, clear out the auto-scroll by pasting this code into your console:
And if, for some reason, the page wants to log you out (in my case I was trying to load all of my "Friends" on Facebook so I could mass-unfriend people), paste the following code into the console to prevent the page from reloading:
window.addEventListener('beforeunload',function(e){e.returnValue = 'sure?';return 'sure?'});