Skip to content

Instantly share code, notes, and snippets.

@elisee
Last active August 29, 2015 14:06
Show Gist options
  • Save elisee/c77098bd168d2b1ceb6e to your computer and use it in GitHub Desktop.
Save elisee/c77098bd168d2b1ceb6e to your computer and use it in GitHub Desktop.
Simple Sprite & TextSprite classes for THREE.js
THREE = require 'three'
module.exports = class Sprite extends THREE.Mesh
constructor: (texture, @frameWidth, @frameHeight, @yOffset = 0) ->
@frameWidth ?= texture.image.width
@frameHeight ?= texture.image.height
geometry = new THREE.PlaneGeometry @frameWidth, @frameHeight
material = new THREE.MeshBasicMaterial map: texture, alphaTest: 0.1, side: THREE.DoubleSide
THREE.Mesh.call @, geometry, material
@setFrame 0
setFrame: (frame) ->
uvs = @geometry.faceVertexUvs[0]
frameX = frame % (@material.map.image.width / @frameWidth)
frameY = Math.floor(frame / (@material.map.image.width / @frameWidth))
left = ( frameX * @frameWidth) / @material.map.image.width
right = ((frameX+1) * @frameWidth) / @material.map.image.width
top = ( @material.map.image.height - @yOffset - frameY * @frameHeight) / @material.map.image.height
bottom = ( @material.map.image.height - @yOffset - (frameY+1) * @frameHeight) / @material.map.image.height
# bottom left
uvs[0][0].set left, bottom
# top right
uvs[1][1].set right, top
# top left
uvs[0][1].set left, top
uvs[1][0].set left, top
# bottom right
uvs[0][2].set right, bottom
uvs[1][2].set right, bottom
@geometry.uvsNeedUpdate = true
return
Sprite = require './Sprite'
THREE = require 'three'
module.exports = class TextSprite extends Sprite
constructor: (text, options) ->
text ?= ''
options ?= {}
options.width ?= 200
options.height ?= 30
options.textAlign ?= 'center'
canvas = document.createElement 'canvas'
canvas.width = options.width
canvas.height = options.height
@ctx = canvas.getContext '2d'
@ctx.fillStyle = 'rgba(100, 100, 100, 0.8)'
@ctx.textAlign = options.textAlign
@ctx.textBaseline = 'middle'
@ctx.font = "#{options.fontWeight ? ''} #{options.fontSize ? 20}px Arial"
@texture = new THREE.Texture canvas
@setText text
super @texture
@material.transparent = true
setText: (text) ->
@ctx.clearRect 0, 0, @ctx.canvas.width, @ctx.canvas.height
text ?= ''
switch @ctx.textAlign
when 'left' then @ctx.fillText text, 0, @ctx.canvas.height / 2
when 'center' then @ctx.fillText text, @ctx.canvas.width / 2, @ctx.canvas.height / 2
when 'right' then @ctx.fillText text, @ctx.canvas.width, @ctx.canvas.height / 2
@texture.needsUpdate = true
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment