可以将2D画布用作立方体的纹理吗?

3

我想在一个立方体的一个面上添加图像,可能使用2D画布元素作为面纹理。这是我的代码,但我不能得到想要的结果。使用画布作为纹理的面是空白的,其他面使用THREE.ImageUtils.loadTexture,并且它们很好。

var renderer, camera, scene;
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var image0 = new Image();
var image1 = new Image();

image0.onload = function() {
    context.drawImage(image0, 0, 0);
};
image0.src = 'textures/nx.jpg';

var texture = new THREE.Texture(canvas);

texture.needsUpdate = true;

init();
animate();

function init(){
    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
    camera.position.z = 400;

    scene = new THREE.Scene();

    var materialArray = [];
    materialArray.push(new THREE.MeshBasicMaterial( { map: texture }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/ny.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/nz.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/px.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/py.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/pz.jpg' ) }));

    var geometry = new THREE.CubeGeometry( 400, 400, 400 );
    var DiceBlueMaterial = new THREE.MeshFaceMaterial(materialArray);
    mesh = new THREE.Mesh( geometry, DiceBlueMaterial);
    scene.add( mesh );
    window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function animate() {
    requestAnimationFrame( animate );

    mesh.rotation.x += 0.005;
    mesh.rotation.y += 0.01;

    renderer.render( scene, camera );
}
1个回答

6
< p > texture.needsUpdate 可能设置得太早了。请尝试以下方法:

var texture = new THREE.Texture(canvas);

image0.onload = function() {
    context.drawImage(image0, 0, 0);
    texture.needsUpdate = true;
};
image0.src = 'textures/nx.jpg';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接