是否可以使用 2d 画布作为立方体的纹理? [英] Is it possible to use a 2d canvas as a texture for a cube?

查看:14
本文介绍了是否可以使用 2d 画布作为立方体的纹理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add images to one face of a cube, possibly using a 2d canvas element as the face texture. Here is my code, but I can't get the result I want. The face using the canvas as a texture is blank, the other faces use a THREE.ImageUtils.loadTexture and they're fine.

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

推荐答案

texture.needsUpdate 可能设置得太早了.试试这个:

The texture.needsUpdate is probably being set too early. Try this:

var texture = new THREE.Texture(canvas);

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

这篇关于是否可以使用 2d 画布作为立方体的纹理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆