Sprite Texture Atlas Manager canvas example

Sprite Texture Atlas Manager canvas example for https://github.com/Leeft/three-sprite-texture-atlas-manager

by Lianna Eeftinck

HTML

<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.6/es6-shim.js"></script>
<script src="https://rawgit.com/Leeft/three-sprite-texture-atlas-manager/master/dist/three-sprite-texture-atlas-manager.umd.js"></script>
<h3>Canvas only example for <a href="https://github.com/Leeft/three-sprite-texture-atlas-manager" target="_new">https://github.com/Leeft/three-sprite-texture-atlas-manager</a></h3>

<p id="canvases"></p>

CSS

p {
  padding: 3em;
  width: 80%;
}

canvas {
  border: 2px solid red;
  margin: 1em 0.5em;
  max-width: 100%;
  max-height: auto;
}

JavaScript

// Note: currently using an old build of the UMD build, as the new one won't
// load here. Functionally they're the same. If you can, use ES6 modules!

// We want textures of 1024x1024 pixels (always a power of two)
var textureManager = new window.threeSpriteAtlasTextureManager(1024);
// Make the sprite allocation code render some blue, purple and screen
// borders in the nodes (this helps visualisation)
textureManager.debug = true;

var words = [
  'This', 'is', 'a', 'basic example', 'of', 'building', 'a',
  'texture atlas', 'to', 'build', 'unique', 'sprites', 'and share',
  'as', 'much', 'GPU', 'memory', 'as possible'
];

// Some settings for the text we're creating
var fontStyle = "Bold 120px 'Segoe UI', 'Lucida Grande', 'Tahoma', 'Calibri', 'Roboto', sans-serif";
// A bit of space around the text to try to avoid hitting the edges
var xPadding = 30;
var yPadding = 30;
// Shift the text rendering up or down
var yOffset = -5;

// Need a canvas to determine the text size
var canvas = document.createElement('canvas');
// but its size doesn't matter
canvas.width = canvas.height = 1;

// Keep track of the promises for each node we're creating so that
// we can tell when they're all done
var nodes = [];

words.forEach(function(text) {
  // Calculate the width of the text
  var width = widthOfText(text) + xPadding;
  // You'd base this height on your font size, may take some fiddling
  var height = 120 + yPadding;

  // Allocate a node for the text'.
  var node = textureManager.allocate(width, height);
  var context = node.clipContext();
  context.font = fontStyle;
  context.textAlign = 'center';
  context.textBaseline = 'middle';
  context.fillStyle = 'rgb( 0, 0, 0 )';
  context.fillText(text, 0, yOffset);
  node.restoreContext();

  // If we were using WebGL for this example, here'd you'd be
  // creating your sprite. node.texture will be a cloned texture
  // ready to use, with its UV coordinates already set:
  // var material = new THREE.SpriteMaterial({ map:...