Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created November 6, 2014 16:49
Show Gist options
  • Save mattdesl/98bef3d3b751cf7999e3 to your computer and use it in GitHub Desktop.
Save mattdesl/98bef3d3b751cf7999e3 to your computer and use it in GitHub Desktop.
immediate texture upload for threejs
/*
Uploads to GPU immediately when the image is ready, then fires callback.
//takes a string path or image/canvas/video/ImageData
uploadTexture(renderer, pathOrImage, function(err, texture) {
if (err) console.error(err)
//do something with the ThreeJS 'texture' result
})
*/
var THREE = require('three');
function upload(renderer, texture, callback) {
texture.needsUpdate = true
renderer.setTexture(texture, 0) //sync GPU upload
callback(null, texture)
}
function uploadCanvas(renderer, data, callback) {
var tex = new THREE.Texture()
tex.image = data
upload(renderer, tex, callback)
}
module.exports = function(renderer, data, callback) {
if (typeof callback !== 'function')
callback = function(){}
if (typeof data === 'string') {
function success(texture) {
upload(renderer, texture, callback)
}
function error() {
//provide an empty Texture
callback("could not load image: "+data, new THREE.Texture())
}
THREE.ImageUtils.loadTexture(data, undefined, success, error)
} else {
uploadCanvas(renderer, data, callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment