问题
I tried adding texture to my cube I made using JS/THREE.JS. But when I open it up in my browser its all black?
This is my code:
<html>
<head>
<title>My first Three.js app</title>
<style>canvas { width: 100%; height: 100% }</style>
</head>
<body>
<script src="https://rawgithub.com/mrdoob/three.js/master/build/three.js"></script>
<script>
// revolutions per second
var angularSpeed = 0.2;
var lastTime = 0;
// this function is executed on each animation frame
function animate(){
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
cube.rotation.y += angleChange;
lastTime = time;
// render
renderer.render(scene, camera);
// request new frame
requestAnimationFrame(function(){
animate();
});
}
// renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// camera
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 500;
// scene
var scene = new THREE.Scene();
// material
var material = new THREE.MeshLambertMaterial({
map: THREE.ImageUtils.loadTexture('crate.jpg')
});
// cube
var cube = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200), material);
cube.overdraw = true;
cube.rotation.x = Math.PI * 0.1;
scene.add(cube);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0xbbbbbb);
scene.add(ambientLight);
// directional lighting
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// start animation
animate();
</script>
</body>
</html>
I used this guide to do it: http://www.html5canvastutorials.com/three/html5-canvas-webgl-texture-with-three-js/
回答1:
It might be because of having MeshLambertMaterial which needs ambient light, which you have but it may not be set correctly. Try using MeshBasicMaterial instead.
回答2:
I've tested the same code you put and it works perfectly.
The only thing I've changed is the path to the image:
map: THREE.ImageUtils.loadTexture('img/textures/test.png')
Double check that the image is located in the current folder and if it is, try with another image (this one works perfect for me: https://aec-apps.com/sites/default/files/styles/app_160_160/public/Screen%20Shot%202013-10-25%20at%2000.28.49.png).
Hope it helps!
来源:https://stackoverflow.com/questions/18633657/three-js-cube-black-but-i-added-texture