Solved: How to Use Embedded Base64 Image Data as Texture in ThreeJS

This problem was one that was making me want to drive a school-bus full of orphan kittens into a volcano.

A little background. I have been doing a few projects which involve using WebGL/ThreeJS within iOS. (More about how to use WebGL natively on iOS in this article I wrote)

To make my life easier with WKWebView I have been compressing javascripts, stylesheets and even images into a single html to circumvent the limitations of the sandboxed environment iOS apps enforce.

It’s the images which have been giving me a headache. To be specific, using base64 encoded image data as a texture on ThreeJS.

I have tried a stupid amount of variations which have worked sometimes and other times not at all; like using document.appendChild and injecting the data to the texture and flagging it for update at various points within runtime. It’s just weird to see something work flawlessly within one code base and breaking on another.

In any case, for future reference, the tried, tested, and successful way of using a base64 encoded images, embedded in an html, as a ThreeJS texture:

  var texture_image = new Image();

  texture_image.src = texture_image_data;
  // ** texture_image_data is a string containing the base64 data

  texture = new THREE.Texture();

  texture_image.onload = function () {
    texture.image = texture_image;
    texture.needsUpdate = true;

The magic snippet is the onload function you see there.

Seems legit!

Show Comments