Alex
Alex

Reputation: 44295

How to load image data instead of an image in javascript with THREE?

I have a javascript piece which loads an image:

var loader = new THREE.TextureLoader();
loader.load( 'textures/canvas1.png', function ( texture ) {
    var geometry = new THREE.SphereGeometry( 200, 20, 20 );
    var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
    var mesh = new THREE.Mesh( geometry, material );
    group.add( mesh );
} );

and works fine. Now, however, I do not want to load an image but a dynamically created image map, created as follows:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var image = context.createImageData(map_width, map_height);
var data = image.data;               
var scale = 5.18;
for (var x = 0; x < map_width; x++) {                  
    for (var y = 0; y < map_height; y++) {
        var nx = x/map_width-0.5;
        var ny = y/map_height-0.5;                    
        var value = Math.abs(noise.perlin2(scale*nx, scale * ny));
        value *= 256;

        var cell = (x + y * map_width) * 4;                    
        data[cell] = data[cell + 1] = data[cell + 2] = Math.pow(1.2, value);                              
        data[cell + 3] = 255; // alpha.                                    
    }
}

I tried the following piece of code (including to create a Uint8Array as suggested in the comments), but all I get is a complete black sphere:

var buffer = new ArrayBuffer(data.length);
var udata = new Uint8Array(buffer);
for (var i=0; i<data.length; i++) {
    udata[i] = data[i];     
}

var geometry = new THREE.SphereGeometry( 200, 20, 20 );
var texture = new THREE.DataTexture(udata, map_width, map_height, THREE.RGBAFormat );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
group.add( mesh );

Maybe the data must be given in a different format?

Upvotes: 1

Views: 2797

Answers (1)

WestLangley
WestLangley

Reputation: 104763

Here is the pattern to follow to create a DataTexture and use it as the map for your material:

var data = new Uint8Array( 4 * size );

// initialize data. . .

var texture = new THREE.DataTexture( data, width, height, THREE.RGBAFormat );

texture.type = THREE.UnsignedByteType;

var material = new THREE.MeshBasicMaterial( { map: texture } );

var mesh = new THREE.Mesh( geometry, material );

scene.add( mesh );

three.js r.128

Upvotes: 2

Related Questions