My sphere, or scene, disappears when I put in OrbitControls - three.js

I have a sphere made with three.js
var canvas = document.querySelector('canvas');
var width = canvas.offsetWidth,
height = canvas.offsetHeight;
var renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true,
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
renderer.setSize(width, height);
renderer.setClearColor(0x000000,0);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(0, 0, 300);
var sphere = new THREE.Group();
scene.add(sphere);
var material = new THREE.LineBasicMaterial({
color: 0xfe0e55
});
var linesAmount = 40;
var radius = 50;
var verticesAmount = 900;
for(var j=0;j<linesAmount;j++){
var index = j;
var geometry = new THREE.Geometry();
geometry.y = (index/linesAmount) * radius*2;
for(var i=0;i<=verticesAmount;i++) {
var vector = new THREE.Vector3();
vector.x = Math.cos(i/verticesAmount * Math.PI*2);
vector.z = Math.sin(i/verticesAmount * Math.PI*2);
vector._o = vector.clone();
geometry.vertices.push(vector);
}
var line = new THREE.Line(geometry, material);
sphere.add(line);
}
function updateVertices (a) {
for(var j=0;j<sphere.children.length;j++){
var line = sphere.children[j];
line.geometry.y += 0.1;
if(line.geometry.y > radius*2) {
line.geometry.y = 0;
}
var radiusHeight = Math.sqrt(line.geometry.y * (2*radius-line.geometry.y));
for(var i=0;i<=verticesAmount;i++) {
var vector = line.geometry.vertices[i];
var ratio = noise.simplex3(vector.x*0.009, vector.z*0.009 + a*0.0006, line.geometry.y*0.009) * 15;
vector.copy(vector._o);
vector.multiplyScalar(radiusHeight + ratio);
vector.y = line.geometry.y - radius;
}
line.geometry.verticesNeedUpdate = true;
}
}
function render(a) {
requestAnimationFrame(render);
updateVertices(a);
renderer.render(scene, camera);
}
function onResize() {
canvas.style.width = '';
canvas.style.height = '';
width = canvas.offsetWidth;
height = canvas.offsetHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
requestAnimationFrame(render);
window.addEventListener("mousemove", onMouseMove);
var resizeTm;
window.addEventListener("resize", function(){
resizeTm = clearTimeout(resizeTm);
resizeTm = setTimeout(onResize, 200);
});
/
<body class="demo-4">
<main>
<div class="content">
<canvas class="scene scene--full" id="scene"></canvas>
<div class="content__inner">
<h2 class="content__title"></h2>
<h3 class="content__subtitle"></h2>
</div>
</div>
</main>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/demo.js"></script>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/three.min.js"></script>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/perlin.js"></script>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/TweenMax.min.js"></script>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/demo4.js"></script>
<script src="/Users/VICSIDIOUS/Desktop/WWW/WWW.VICSIDIOUS.COM/VICSIDIOUS_2018/OrbitControls.js"></script>
</body>
But when I try to add OrbitControls, everything disappears.
Yes, I am referencing OrbitControl.js
I've tried using domElement
I've adjusted the camera like crazy, still no luck
I guess my question is, for anyone experienced with three.js, is there anything in the code that may be conflicting with OrbitControls?
I literally started learning web dev two weeks ago. Please keep that in mind, I'm just looking to learn and doing my best not to ask questions without researching a lot first.
Thank you so much.

Okay, like I said, I am a beginner, so please try not to roll your eyes!
I think I solved it by just calling the OrbitControls script before the line where I called the demo4 (sphere) script in the index file.
I have a new problem though: the whole thing is putting a mighty dent on performance. When I run the index page, my whole computer runs slow. It's like the graphics are too heavy?
I will do some research on optimization, I spent all day today trying to understand how the script was constructing the sphere (I took it from a website). I found it interesting that it's actually not rendering a sphere (it's a THREE), it's just rendering and updating lines in a wobbly spherical shape.
Even though the solution was anticlimactic, I learned a lot about three.js trying to solve this problem. Looking forward to see if it can be optimized and made to run smoothly!

Related

How to make particles in threejs take the shape of a model/object -onscroll

I am relatively new to ThreeJS.
I want to make a website very similar to this one:
Web de CraftedBYGC
In which I make a system of particles that as the user scrolls they disperse and rejoin in a form.
The truth is that I am very lost about where to start.
I would greatly appreciate some help.
I tried to create a geometry with particle mesh and move the camera on scroll to simulate a little bit the effect, but the truth was very poor. I need to find another method and I don't know well what to do...
Below is a snippet of the working example:
var webGLRenderer = initRenderer();
var scene = new THREE.Scene();
var camera = initCamera(new THREE.Vector3(-30, 40, 50));
// call the render function
var step = 0;
var knot;
// setup the control gui
var controls = new function () {
// we need the first child, since it's a multimaterial
this.radius = 13;
this.tube = 1.7;
this.radialSegments = 156;
this.tubularSegments = 12;
this.redraw = function () {
// remove the old plane
if (knot) scene.remove(knot);
// create a new one
var geom = new THREE.TorusKnotGeometry(controls.radius, controls.tube, Math.round(controls.radialSegments), Math.round(controls.tubularSegments), Math.round(controls.p), Math.round(controls.q));
knot = createPoints(geom);
// add it to the scene.
scene.add(knot);
};
};
var gui = new dat.GUI();
gui.add(controls, 'radius', 0, 40).onChange(controls.redraw);
gui.add(controls, 'tube', 0, 40).onChange(controls.redraw);
gui.add(controls, 'radialSegments', 0, 400).step(1).onChange(controls.redraw);
gui.add(controls, 'tubularSegments', 1, 20).step(1).onChange(controls.redraw);
controls.redraw();
render();
// from THREE.js examples
function generateSprite() {
var canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
var context = canvas.getContext('2d');
var gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(0.2, 'rgba(0,255,255,1)');
gradient.addColorStop(0.4, 'rgba(0,0,64,1)');
gradient.addColorStop(1, 'rgba(0,0,0,1)');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
}
function createPoints(geom) {
var material = new THREE.PointsMaterial({
color: 0xffffff,
size: 3,
transparent: true,
blending: THREE.AdditiveBlending,
map: generateSprite(),
depthWrite: false // instead of sortParticles
});
var cloud = new THREE.Points(geom, material);
return cloud;
}
function render() {
knot.rotation.y = step += 0.01;
// render using requestAnimationFrame
requestAnimationFrame(render);
webGLRenderer.render(scene, camera);
}
body {
margin: 0;
overflow: none
}
<!DOCTYPE html>
<html>
<head>
<title>Example 07.11 - 3D Torusknot</title>
<script type="text/javascript" charset="UTF-8" src="https://www.smartjava.org/ltjs3/libs/three/three.js"></script>
<script src="https://www.smartjava.org/ltjs3/libs/three/controls/TrackballControls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.9/dat.gui.min.js"></script>
<script src="https://www.smartjava.org/ltjs3/src/js/util.js"></script>
</head>
<body>
<div id="webgl-output">
</body>
</html>
This is working on a TorusKnot, but you can apply the particles to a model, too. All you have to do is change the source.

Threejs texture map to sphere error (three.min.js:120 THREE.WebGLRenderer: image is not power of two (1000x500))

I am learning three js now. What I am trying to do now is draw a sphere and then texture map an image on the sphere. Basically, I am following this tutorial, http://learningthreejs.com/blog/2013/09/16/how-to-make-the-earth-in-webgl/.
This is my code
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script type="text/javascript">
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
window.addEventListener('resize', function() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
})
controls = new THREE.OrbitControls(camera, renderer.domElement);
var geometry = new THREE.SphereGeometry(0.5, 32, 32)
var material = new THREE.MeshPhongMaterial();
var earthMesh = new THREE.Mesh(geometry, material)
scene.add(earthMesh)
// TheJim01: Replacing local file with accessible web resource
// License and source: https://commons.wikimedia.org/wiki/File:Earthmap1000x500compac.jpg
//material.map = THREE.ImageUtils.loadTexture("world.jpg");
material.map = THREE.ImageUtils.loadTexture("https://upload.wikimedia.org/wikipedia/commons/c/c4/Earthmap1000x500compac.jpg");
camera.position.z = 10; //3
//game logic
var update = function() {
};
//draw scene
var render = function() {
renderer.render(scene, camera);
}
// run game loop (update, render, repeat)
var GameLoop = function() {
requestAnimationFrame(GameLoop);
update();
render();
}
GameLoop();
</script>
When I run the code, I got this error in the console.
three.min.js:120 THREE.WebGLRenderer: image is not power of two (1000x500)
My image file actually have 1000X500 size as well. But nothing is displayed on the canvas. What is wrong and how can I fix it?
I was unable to load the texture without errors (in three.js r93) with THREE.ImageUtils.loadTexture. It threw a "tainted canvas" error in Chrome. I switched to using THREE.TextureLoader, which you can see in the code below.
All that said, that was probably not the real problem. Your scene is lacking a light, and without a light, everything will render as black. In the code below, I added a simple point light to the camera.
With those two fixes in place, your code runs as expected.
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script type="text/javascript">
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
window.addEventListener('resize', function() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
})
controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(camera);
camera.add(new THREE.PointLight(0xfffff, 1, Infinity));
var geometry = new THREE.SphereGeometry(0.5, 32, 32)
var material = new THREE.MeshPhongMaterial();
var earthMesh = new THREE.Mesh(geometry, material)
scene.add(earthMesh)
// TheJim01: Replacing local file with accessible web resource
// License and source: https://commons.wikimedia.org/wiki/File:Earthmap1000x500compac.jpg
//material.map = THREE.ImageUtils.loadTexture("world.jpg");
var loader = new THREE.TextureLoader();
material.map = loader.load("https://upload.wikimedia.org/wikipedia/commons/c/c4/Earthmap1000x500compac.jpg");
camera.position.z = 10; //3
//game logic
var update = function() {
};
//draw scene
var render = function() {
renderer.render(scene, camera);
}
// run game loop (update, render, repeat)
var GameLoop = function() {
requestAnimationFrame(GameLoop);
update();
render();
}
GameLoop();
</script>

Particle Sphere not fully drawn when looping through vertices

I am drawing a sphere in THREEJS with particles. That works good.
However i loop trough those points to animate(reposition them). Works just fine when i use widthSegments under 50(WidthSegement is the 2nd argument). Anything above 50 will stop being drawn.
For reference:
SphereGeometry(radius, widthSegments, heightSegments)
This would work fine:
let geometry = new THREE.SphereGeometry(30, 50, 20);
And produce this effect:
if i go with like 100 segments for example i would get this result:
However this only happens when i loop trough the points to alter their position.
It still animates the existing points. but not any others.
//Related to the audio api
let AudioContext = window.AudioContext || window.webkitAudioContext,
ctxAudio = new AudioContext(),
sampleRate = ctxAudio.sampleRate,
audio = document.getElementById("sound"),
audioSrc = ctxAudio.createMediaElementSource(audio),
analyser = ctxAudio.createAnalyser(),
bufferLength = analyser.frequencyBinCount,
dataArray = new Uint8Array(bufferLength);
analyser.fftSize = 2048 * 2;
analyser.smoothingTimeConstant = 0.75;
audioSrc.connect(analyser);
audioSrc.connect(ctxAudio.destination);
//Setting up the renderer
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//Defining the objects in the scene
let geometry = new THREE.SphereGeometry(30, 100, 20);
let loader = new THREE.TextureLoader();
loader.crossOrigin = true;
let particleTexture = loader.load('https://threejs.org/examples/textures/particle2.png');
let material = new THREE.PointsMaterial({
color: 0x20C9BD,
size: 1,
transparent: true,
blending: THREE.AdditiveBlending,
map: particleTexture,
depthWrite: false
});
let points = new THREE.Points(geometry, material);
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
//Setting the scene
scene.add(points);
camera.position.z = 100;
//Copy the default sphere into a vector
const def = new THREE.Vector3;
for (let i = 0; i < geometry.vertices.length; i++) {
def[i] = {
x: geometry.vertices[i].x,
y: geometry.vertices[i].y,
z: geometry.vertices[i].z
};
}
//Render the scene(looping through it 60 times a second)
//This is where the issue is
function render() {
requestAnimationFrame(render);
analyser.getByteFrequencyData(dataArray);
camera.lookAt(points.position);
for (let i = 0; i < geometry.vertices.length; i++) {
let particle = geometry.vertices[i];
let dx = def[i].x * (dataArray[i] / 255.0) + def[i].x;
let dy = def[i].y * (dataArray[i] / 255.0) + def[i].y;
let dz = def[i].z * (dataArray[i] / 255.0) + def[i].z;
particle.set(dx, dy, dz); //<--this is where the issue is.
}
geometry.verticesNeedUpdate = true;
renderer.render(scene, camera);
}
render();
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/three.js"></script>
</head>
<body>
<audio id="sound" controls src="http://tackj.happyvisocoders.be/audio/DieForYou-Starset.mp3"></audio>
</body>
</html>
If you comment out the particle.set(dx,dy,dz) it draws perfectly.
However this animates the particles to move along with the music. So its important to keep this part.
Why doesn't the sphere draw completly and how can i fix this?
This has in fact little to do with three.js but more with the webaudio-API.
When you are creating the analyzer with an FFT-size of 2048, you will get 1024 frequency bins (see analyzer.frequencyBinCount), but your geometry has 1902 vertices. So for vertices with index 1024 to 1901, dataArray[i] is undefined, and the calculations all resolve to NaN. Now you are setting the vector as vector.set(NaN, NaN, NaN) and three.js has no Idea what to make of this so the points don't get rendered.
So if you replace that part of the loop with
let fftValue = (dataArray[i] / 255.0) || 0;
let dx = def[i].x * fftValue + def[i].x;
let dy = def[i].y * fftValue + def[i].y;
let dz = def[i].z * fftValue + def[i].z;
particle.set(dx, dy, dz);
or even simpler:
let fftValue = (dataArray[i] / 255.0) || 0;
geometry.vertices[i]
.copy(def)
.multiplyScalar(1 + fftValue)
you should be alright.

three js drag and drop Uncaught TypeError

I have been trying to implement the drag and drop functionality found here...
http://www.smartjava.org/tjscb/07-animations-physics/07.08-drag-n-drop-object-around-scene.html
Whenever I customise it slightly and use it in my project I get the following..
"Uncaught TypeError: Cannot read property 'point' of undefined"
whenever I try to drag a cube. The rotation isn't occurring so it must be recognising that I'm trying to drag an object and it relates to this line of code..
"selectedObject.position.copy(intersects[0].point.sub(offset))"
I assumed since I am new to all of this that I had messed up, so I copied all of the code from the link above into a new page (so should be identical) and ran it and I get the same thing (everything else works good)
Im probably missing something really stupid, I have searched for this and looked at other examples on how to achieve this, but since I was working my way through a book which explained everything I thought I would stick with this, and also it would be a good learning experience to figure out why its not working. If anyone could point me in the right direction I would appreciate it
<!DOCTYPE html>
<html>
<head>
<title>07.08 - Drag and drop object around scene</title>
<script type="text/javascript" src="js/threejs/three.min.js"></script>
<script type="text/javascript" src ="js/threejs/OrbitControls.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
<script>
// global variables
var renderer;
var scene;
var camera;
var cube;
var control;
var orbit;
// used for drag and drop
var plane;
var selectedObject;
var offset = new THREE.Vector3();
var objects = [];
// based on http://mrdoob.github.io/three.js/examples/webgl_interactive_draggablecubes.html
function init() {
// create a scene, that will hold all our elements such as objects, cameras and lights.
scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// create a render, sets the background color and the size
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xffffff, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 18, 18), new THREE.MeshBasicMaterial({
color: 0x00ff00,
opacity: 0.25,
transparent: true
}));
plane.visible = false;
scene.add(plane);
var dirLight = new THREE.DirectionalLight();
dirLight.position.set(25, 23, 15);
scene.add(dirLight);
var dirLight2 = new THREE.DirectionalLight();
dirLight2.position.set(-25, 23, 15);
scene.add(dirLight2);
for (var i = 0; i < 200; i++) {
// create a cube and add to scene
var cubeGeometry = new THREE.BoxGeometry(2, 2, 2);
var cubeMaterial = new THREE.MeshLambertMaterial({color: Math.random() * 0xffffff});
cubeMaterial.transparent = true;
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
objects.push(cube);
cube.scale.x = Math.random() + 0.5 * 2;
cube.scale.y = Math.random() + 0.5 * 2;
cube.scale.z = Math.random() + 0.5 * 2;
cube.position.x = Math.random() * 50 - 25;
cube.position.y = Math.random() * 50 - 25;
cube.position.z = Math.random() * 50 - 25;
cube.rotation.x = Math.random() * Math.PI * 2;
cube.rotation.y = Math.random() * Math.PI * 2;
cube.rotation.z = Math.random() * Math.PI * 2;
scene.add(cube);
}
// position and point the camera to the center of the scene
camera.position.x = 35;
camera.position.y = 35;
camera.position.z = 53;
camera.lookAt(scene.position);
// add some controls so we can rotate
orbit = new THREE.OrbitControls(camera);
// add the output of the renderer to the html element
document.body.appendChild(renderer.domElement);
// call the render function
render();
}
function render() {
renderer.render(scene, camera);
orbit.update();
requestAnimationFrame(render);
}
document.onmousemove = function (event) {
// make sure we don't access anything else
event.preventDefault();
// get the mouse positions
var mouse_x = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouse_y = -( event.clientY / window.innerHeight ) * 2 + 1;
// get the 3D position and create a raycaster
var vector = new THREE.Vector3(mouse_x, mouse_y, 0.5);
vector.unproject(camera);
var raycaster = new THREE.Raycaster(camera.position,
vector.sub(camera.position).normalize());
// first check if we've already selected an object by clicking
if (selectedObject) {
// check the position where the plane is intersected
var intersects = raycaster.intersectObject(plane);
// reposition the selectedobject based on the intersection with the plane
selectedObject.position.copy(intersects[0].point.sub(offset));
} else {
// if we haven't selected an object, we check if we might need
// to reposition our plane. We need to do this here, since
// we need to have this position before the onmousedown
// to calculate the offset.
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
// now reposition the plane to the selected objects position
plane.position.copy(intersects[0].object.position);
// and align with the camera.
plane.lookAt(camera.position);
}
}
};
document.onmousedown = function (event) {
// get the mouse positions
var mouse_x = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouse_y = -( event.clientY / window.innerHeight ) * 2 + 1;
// use the projector to check for intersections. First thing to do is unproject
// the vector.
var vector = new THREE.Vector3(mouse_x, mouse_y, 0.5);
// we do this by using the unproject function which converts the 2D mouse
// position to a 3D vector.
vector.unproject(camera);
// now we cast a ray using this vector and see what is hit.
var raycaster = new THREE.Raycaster(camera.position,
vector.sub(camera.position).normalize());
// intersects contains an array of objects that might have been hit
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
orbit.enabled = false;
// the first one is the object we'll be moving around
selectedObject = intersects[0].object;
// and calculate the offset
var intersects = raycaster.intersectObject(plane);
offset.copy(intersects[0].point).sub(plane.position);
}
};
document.onmouseup = function (event) {
orbit.enabled = true;
selectedObject = null;
}
// calls the init function when the window is done loading.
window.onload = init;
</script>
</head>
<body>
</body>
</html>
"Uncaught TypeError: Cannot read property 'point' of undefined"
"selectedObject.position.copy(intersects[0].point.sub(offset))"
This means, intersects[0] is undefined which means the array intersects has no element (length = 0). You are using raycasting and it isn't working properly.
You should share your modified code so that we can check what is going wrong in your raycasting.
Update: I think your three.js version is greater than 71 while three.js version of this website is 71 or less. In the 72th version, there is an update in the raycaster -
Ignore invisible objects. (#mrdoob, #tschw)
So, the problem is here -
var intersects = raycaster.intersectObject(plane);
Since the plane is invisible, the intersectObject is returning empty array.
Workaround: I found a workaround. You can remove the following line -
plane.visible = false;
You can hide the material of the plane instead in the following way -
plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 18, 18), new THREE.MeshBasicMaterial({
color: 0xffff00,
opacity: 0.50,
transparent: true,
visible: false
}));
In this way, the raycaster will work properly and the plane will be invisible as well.

three.js cube black but i added texture?

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/
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.
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!

Resources