如何在三维javascript中加载图像数据而不是图像?

时间:2015-11-05 15:14:41

标签: javascript three.js

我有一个加载图片的javascript片段:

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 );
} );

并且工作正常。但是,现在,我不想加载图像,而是加载动态创建的图像映射,如下所示:

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.                                    
    }
}

我尝试了以下一段代码(包括根据评论中的建议创建Uint8Array),但我得到的只是一个完整的黑色球体:

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 );

也许必须以不同的格式提供数据?

1 个答案:

答案 0 :(得分:1)

当您将纹理创建为DataTexture并将其用作材料的map时,您需要记住设置needsUpdate标记。

以下是您可以遵循的模式:

var data = new Uint8Array( 4 * size );

// initialize data. . .

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

texture.type = THREE.UnsignedByteType;

texture.needsUpdate = true; // required

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

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

scene.add( mesh );

three.js r.73