Three.js WebGLRenderered videos don't play on android phones - three.js

The video texture example below does not seem to work on android LG nexus phone although all other non video examples work including the youtube example on three.js.
Does anyone else have this issue? I am trying to render video using THREE.WebGLRenderer so that I can ultimately use stereo effect with it to use it with VR (like google cardboard) kit. So far only CSS3DRenderer/Canvas rendered videos seem to work on the phone. But I can't use these renderers because stereo effect does not work with these renderers (i.e effect = new THREE.StereoEffect(renderer);)
http://mrdoob.github.io/three.js/examples/webgl_materials_video.html
Please let me know if there is to get videos render with stereo effect.
UPDATE---------------CODE ON HAND (Adapted from http://stemkoski.github.io/Three.js/Video.html)
<!doctype html>
<html lang="en">
<head>
<title>Video Texture (Three.js)</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<!-- <link rel=stylesheet href="css/base.css"/> -->
</head>
<body>
<script src="js/three.min.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/effects/StereoEffect.js"></script>
<div id="ThreeJS"></div>
<script>
var container, scene, camera, renderer, controls, stats, effect, element;
var video, videoImage, videoImageContext, videoTexture;
init();
animate();
// FUNCTIONS
function init()
{
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,150,400);
camera.lookAt(scene.position);
renderer = new THREE.WebGLRenderer( {antialias:true} );
//effect = new THREE.StereoEffect(renderer);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
element= renderer.domElement;
//effect.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( element );
// CONTROLS
controls = new THREE.OrbitControls( camera, element );
element.addEventListener('click', fullscreen, false);
// LIGHT
var light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
///////////
// VIDEO //
///////////
// create the video element
video = document.createElement( 'video' );
//video.id = 'video';
video.type = ' video/mp4; codecs="theora, vorbis" ';
video.src = "video/sintel.ogv";
video.load(); // must call after setting/changing source
video.play();
videoImage = document.createElement( 'canvas' );
videoImage.width = 320;
videoImage.height = 240;
videoImageContext = videoImage.getContext( '2d' );
// background color if no video present
videoImageContext.fillStyle = '#000000';
videoImageContext.fillRect( 0, 0, videoImage.width, videoImage.height );
videoTexture = new THREE.Texture( videoImage );
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
var movieMaterial = new THREE.MeshBasicMaterial( { map: videoTexture, overdraw: true, side:THREE.DoubleSide } );
// the geometry on which the movie will be displayed;
// movie image will be scaled to fit these dimensions.
var movieGeometry = new THREE.PlaneGeometry( 240, 100, 4, 4 );
var movieScreen = new THREE.Mesh( movieGeometry, movieMaterial );
movieScreen.position.set(0,50,00);
scene.add(movieScreen);
camera.position.set(0,150,300);
camera.lookAt(movieScreen.position);
window.addEventListener('resize', resize, false);
setTimeout(resize, 1);
}
function update() {
resize();
camera.updateProjectionMatrix();
controls.update();
}
function animate()
{
requestAnimationFrame( animate );
render();
//update();
}
function fullscreen() {
video.play();
console.log(video);
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.msRequestFullscreen) {
container.msRequestFullscreen();
} else if (container.mozRequestFullScreen) {
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) {
container.webkitRequestFullscreen();
}
}
function resize() {
var width = container.offsetWidth;
var height = container.offsetHeight;
//console.log(container, width,height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
//effect.setSize(width, height);
}
function render()
{
if ( video.readyState === video.HAVE_ENOUGH_DATA )
{
videoImageContext.drawImage( video, 0, 0 );
if ( videoTexture )
videoTexture.needsUpdate = true;
}
renderer.render( scene, camera );
}
</script>
</body>
</html>

On mobile devices videos don't play unless initiated from a user action. So if you execute the init method from a mousedown event listener it should work.

Related

Change the color of 3D model using colorPicker three.js

I am trying to change the color of 3D object where intersected using color picker.I am trying with dat.gui.I want to change the color of 3d part where it gets clicked and change the selected from the colorPicker.I tried out some possible ways but it doesn't work out.Please,refer to the code I tried out. Help me out with some solution and draw my attention to where I am getting wrong. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<title>color</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="three.js"></script>
<script src="OrbitControls.js"></script>
<script src="Detector.js"></script>
<script src="stats.min.js"></script>
<script src="loaders/MTLLoader.js"></script>
<script src="loaders/OBJLoader.js"></script>
<script type='text/javascript' src='DAT.GUI.min.js'></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer,effectController;
var raycaster;
var objects = [];
var selectedObject,selectedPos;
var rotation;
var pos,quat;
var INTERSECTED;
var guiColor;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 15;
controls = new THREE.OrbitControls( camera );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x555000 );
scene.add( camera );
// light
var dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 200, 200, 1000 ).normalize();
camera.add( dirLight );
camera.add( dirLight.target );
var mtlLoader = new THREE.MTLLoader(); mtlLoader.setBaseUrl('assets/'); mtlLoader.setPath('assets/'); mtlLoader.load('anno.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('anno.obj', function (object) {
scene.add( object );
objects.push( object );
});
});
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
/* Controls */
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
raycaster = new THREE.Raycaster();
gui = new dat.GUI();
parameters =
{
color: "#ff0000",
};
gui.add( parameters, 'reset' ).name("Reset");
guiColor = gui.addColor( parameters, 'color' ).name('Color');
container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
renderer.domElement.addEventListener("click", onclick, false);
}
var mouse = new THREE.Vector2();
function onclick(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
INTERSECTED = intersects[0].object;
if ( INTERSECTED && INTERSECTED.material.emissive != null ){
guiColor.onChange(function(){
INTERSECTED.material.emissive.setHex(parameters.color)
});
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
</script>
</body>
</html>
I've create a little live demo with your code and a basic working solution. I'd like to highlight three important changes:
You can use the onChange() event handler in order to know when a certain dat.gui property has changed. The demo uses this feature to update the color of a selected object.
I have refactored your raycasting logic into something more simple. I've seen you've copied some code from the official three.js examples but the new code should be sufficient for your case. Besides, it's also better to update Material.color instead of Material.emissive.
If you set OrbitControls.enableDamping to true, you have to update the controls in your animation loop.
https://jsfiddle.net/btuzd23o/2/
three.js R103

Annotation using three.js

I have two cubes of .obj file.The obj file is render on the browser. I want to do is as the user click on any of the cube or anywhere on the cube one prompt box display to add annotation to that place on the cube.How to do this? I am new to three.js. Anyone can help me out?
Here is my code with.obj file
<!DOCTYPE html>
<html>
<head>
<title>Mouse Picking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="three.js"></script>
<script src="Detector.js"></script>
<script src="OrbitControls.js"></script>
<script src="OBJLoader.js"></script>
<script src="MTLLoader.js"></script>
<script src="DragControls.js"></script>
<style>
body {
overflow: hidden;
margin: 0;
padding: 0;
background: hsl(0, 0%, 10%);
}
</style>
</head>
<body>
<script>
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
}
var container;
var camera, controls, scene, renderer;
var lighting, ambient, keyLight, fillLight, backLight;
var BlueCube, RedCube;
var objects = [];
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
/* Camera */
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.x = 5;
camera.position.y = 3;
camera.position.z = 7;
/* Scene */
scene = new THREE.Scene();
lighting = true;
ambient = new THREE.AmbientLight(0xffffff, 2.5);
scene.add(ambient);
keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);
fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);
backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();
/* Model */
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setBaseUrl('assets/');
mtlLoader.setPath('assets/');
mtlLoader.load('mouse_picking.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('mouse_picking.obj', function (object) {
scene.add( object );
objects.push( object );
});
});
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
/* Renderer */
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color("hsl(0, 0%, 10%)"));
container.appendChild(renderer.domElement);
/* Controls */
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
/* Events */
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
//selected();
requestAnimationFrame(animate);
controls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
I recommend that you subdivide the geometry of the cube mesh, and then use raycasting to determine the part of the scene (specifically, the triangle in the mesh) that was clicked. Then you could add a sprite object, which is a plane that always faces the camera, to display some text.
For more information, check out the collection of examples at http://stemkoski.github.io/Three.js/index.html - they are a little outdated, but the examples "Mouse Click" and "Sprite Text Labels" might help you to get started.

three.js morph animation isnt animating correctly

I am trying implement a simple animation on a icosphere. The animation only consistst of 3 keyframes. Starting position, randomly selected vertices that have been pulled off to the side and then back to starting position. i used these two sources to try to create this.
https://www.youtube.com/watch?v=JKB4aPUkCJw
http://stemkoski.github.io/Three.js/Model-Animation.html
It seems like the animation completely disregards what the json file tells it to do and instead just moves some vertices randomly and then back to starting position.
here is my code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>My first three.js app</title>
<style>
body{
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="three.min.js"></script>
<script src="ColladaLoader.js"></script>
<script src="OrbitControls.js"></script>
<script src="TrackballControls.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
var scene, camera, renderer;
var geometry, material, mesh;
var controls;
var obj, android;
var animOffset = 0, // starting frame of animation
walking = false,
duration = 5000, // milliseconds to complete animation
keyframes = 3, // total number of animation frames
interpolation = duration / keyframes, // milliseconds per frame
lastKeyframe = 0, // previous keyframe
currentKeyframe = 0;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth /
window.innerHeight, 1, 10000 );
camera.position.z = 5;
var light = new THREE.PointLight(0xffffff, 0.9);
light.position.set(0, 100, 10);
scene.add(light);
var light2 = new THREE.PointLight(0xffffff, 0.9);
light.position.set(0, 0, 100);
scene.add(light2);
var light1 = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(light1);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0xb7b7b7);
document.body.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera );
var loader = new THREE.ObjectLoader();
loader.load('/three/star3.json', function (obj){
scene.add(obj);
obj.position.set(0, -0.5, 0);
});
}
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "/three/portstar.json", addModelToScene );
// addModelToScene function is called back after model has loaded
function addModelToScene( geometry, materials )
{
// for preparing animation
for (var i = 0; i < materials.length; i++)
materials[i].morphTargets = true;
var material = new THREE.MultiMaterial( materials );
android = new THREE.Mesh( geometry, material );
android.scale.set(10,10,10);
scene.add( android );
}
function animate() {
controls.update();
render();
requestAnimationFrame( animate );
}
function render(){
if ( android ) // exists / is loaded
{
// Alternate morph targets
time = new Date().getTime() % duration;
keyframe = Math.floor( time / interpolation ) + animOffset;
if ( keyframe != currentKeyframe )
{
android.morphTargetInfluences[ lastKeyframe ] = 0;
android.morphTargetInfluences[ currentKeyframe ] = 1;
android.morphTargetInfluences[ keyframe ] = 0;
lastKeyframe = currentKeyframe;
currentKeyframe = keyframe;
}
android.morphTargetInfluences[ keyframe ] =
( time % interpolation ) / interpolation;
android.morphTargetInfluences[ lastKeyframe ] =
1 - android.morphTargetInfluences[ keyframe ];
}
//obj.rotation.x += 0.5;
renderer.render( scene, camera );
}
init();
render();
animate();
</script>
</body>
Everything has been exported the way showed in the video but i have also tried 30 other export settings trying to figure this out. Also, if anyone has any helpful links that would help me learn three.js feel free to comment them. I would really like to get good at it but i am having alot of trouble.

threejs : error when deleting a Geometry or BufferGeometry in combination with a Sprite/Ortho camera

I load some objects using the ctm binary loader in Threejs r69. This returns Mesh objects using a BufferGeometry internally.
I need to remove from the scene then delete one of these Meshes, including their material/texture/geometry. According to examples and google, I should use:
scene.remove(m_mesh);
m_mesh.geometry.dispose();
m_mesh.geometry = null;
m_mesh.material.dispose();
m_mesh.material = null;
m_mesh = null;
This removes the object from the scene, but the screen goes black for a second, and I've got a GL error :
Error: WebGL: drawElements: no VBO bound to enabled vertex attrib index 2!
Looks like the above sequence (ran in my render() operation, just before drawing the scene) did not clean everything, or at least I still have references to non existing VBOs somewhere.
I've spent quite some time debugging the problem and came to the conclusion that this happens only when using an orthographic camera with a Sprite and a Perspective camera, in 2 differents scenes.
Basically, I draw a flat background using a Sprite and a dedicated scene, then my 3D scene with Meshes. If I delete a mesh from the 3D scene, then the drawing of the flat background fails.
I can't figure out why. Looks like there's a side effect of deleting a Mesh on Sprites, even if attached to different scenes.
If I comment the background drawing, then the deletion of my mesh works perfectly.
I insert below a reproduction of the problem using the standard threejs distribution. Wait about 5 seconds and you should see some GL errors on the jaavscript console.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometries</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="build/three.min.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer;
frame_count = 0;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.y = 400;
// I need a second camera for my 2D sprite (used as a background)
// must use another texture so that it's not destroyed when removing the first object
cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -2,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
1, 10);
cameraOrtho.position.z = 10;
cameraOrtho.position.y = 400;
sceneBackground = new THREE.Scene();
var map1 = THREE.ImageUtils.loadTexture('textures/disturb.jpg');
var material1 = new THREE.SpriteMaterial({
map: map1
});
var spriteBackground = new THREE.Sprite(material1);
spriteBackground.scale.set(window.innerWidth, window.innerHeight, 1);
spriteBackground.position.set(window.innerWidth / 2,
window.innerHeight / 2);
sceneBackground.add(spriteBackground);
scene = new THREE.Scene();
var light;
my_object = null;
scene.add(new THREE.AmbientLight(0x404040));
light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 1, 0);
scene.add(light);
var map = THREE.ImageUtils.loadTexture('textures/UV_Grid_Sm.jpg');
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
var material = new THREE.MeshLambertMaterial({
map: map,
side: THREE.DoubleSide
});
// one object is enough to demonstrate
// can't reproduce the problem with a standard SphereGeometry
// try to convert it to a BufferGeometry
var sphereGeometry = new THREE.SphereGeometry(75, 20, 10);
var bufferGeometry = new THREE.BufferGeometry().fromGeometry(sphereGeometry);
my_object = new THREE.Mesh(bufferGeometry, material);
my_object.position.set(-400, 0, 200);
scene.add(my_object);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.autoClear = false;
renderer.autoClearDepth = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
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);
render();
stats.update();
}
function render() {
frame_count++;
var timer = Date.now() * 0.0001;
camera.position.x = Math.cos(timer) * 800;
camera.position.z = Math.sin(timer) * 800;
camera.lookAt(scene.position);
//after a few frames I want to destroy completely the object
//means remove from the scene, remove texture, material, geometry
//note that here it's a Geometry, not a BufferGeometry
//may be different
if (frame_count > 60 * 5) {
if (my_object != null) {
console.log("destroy object buffer");
scene.remove(my_object);
my_object.material.map.dispose();
my_object.material.dispose();
my_object.geometry.dispose();
my_object = null;
}
}
for (var i = 0, l = scene.children.length; i < l; i++) {
var object = scene.children[i];
object.rotation.x = timer * 5;
object.rotation.y = timer * 2.5;
}
renderer.render(sceneBackground, cameraOrtho);
renderer.clearDepth();
renderer.render(scene, camera);
}
</script>
</body>
</html>
Any hints on how to fix this issue?
Thank you,
Pascal

three.js set background image

How to create a static background image?
For default background:
scene = new THREE.Scene();
// ...
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setClearColor( scene.fog.color, 1 );
How to set a image for scene.fog, or set opacity for clearcolor?
If you are trying to set a static background image (even if you rotate your main camera, the background doesn't change), you have to create 2 scenes and 2 cameras.
The first scene will be composed of a basic plane on which a texture is applied.
The second scene will have all your objects.
Here is a code that would do it :
<html>
<body>
<script src="Three.js"></script>
<script>
var color = 0x000000;
// Create your main scene
var scene = new THREE.Scene();
// Create your main camera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create lights
var light = new THREE.PointLight(0xEEEEEE);
light.position.set(20, 0, 20);
scene.add(light);
var lightAmb = new THREE.AmbientLight(0x777777);
scene.add(lightAmb);
// Create your renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create a cube
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshLambertMaterial({
color: 0xff00ff,
ambient: 0x121212,
emissive: 0x121212
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Set up the main camera
camera.position.z = 5;
// Load the background texture
var texture = THREE.ImageUtils.loadTexture( '1.jpg' );
var backgroundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2, 0),
new THREE.MeshBasicMaterial({
map: texture
}));
backgroundMesh .material.depthTest = false;
backgroundMesh .material.depthWrite = false;
// Create your background scene
var backgroundScene = new THREE.Scene();
var backgroundCamera = new THREE.Camera();
backgroundScene .add(backgroundCamera );
backgroundScene .add(backgroundMesh );
// Rendering function
var render = function () {
requestAnimationFrame(render);
// Update the color to set
if (color < 0xdddddd) color += 0x0000ff;
// Update the cube color
cube.material.color.setHex(color);
// Update the cube rotations
cube.rotation.x += 0.05;
cube.rotation.y += 0.02;
renderer.autoClear = false;
renderer.clear();
renderer.render(backgroundScene , backgroundCamera );
renderer.render(scene, camera);
};
render();
</script>
</body>
</html>
**Demo right here **
Hope this helps.
NOTE (2014/06/28): This code works with the latest release of Three.js: R67
Use Texture loader to load a any image as texture and then apply that to scene like this:
//Load background texture
const loader = new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
Result:
Demo:
See the Pen Flat Earth Three.JS by Hitesh Sahu (#hiteshsahu) on CodePen.
this run:
renderer = new THREE.WebGLRenderer({ antialias: false,alpha:true });
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000, 0);
An background image can be set by setting the scene.background attribute of the THREE.Scene:
scene = new THREE.Scene();
bgTexture = loader.load("https://i.stack.imgur.com/vDUZz.jpg",
function ( texture ) {
var img = texture.image;
bgWidth= img.width;
bgHeight = img.height;
resize();
} );
scene.background = bgTexture;
bgTexture.wrapS = THREE.MirroredRepeatWrapping;
bgTexture.wrapT = THREE.MirroredRepeatWrapping;
The aspect ratio of the image can be adjusted to the aspect ratio of the canvas like this:
var aspect = window.innerWidth / window.innerHeight;
var texAspect = bgWidth / bgHeight;
var relAspect = aspect / texAspect;
bgTexture.repeat = new THREE.Vector2(
Math.max(relAspect, 1),
Math.max(1/relAspect,1) );
bgTexture.offset = new THREE.Vector2(
-Math.max(relAspect-1, 0)/2,
-Math.max(1/relAspect-1, 0)/2 );
See the code snippet:
(function onLoad() {
var container, loader, camera, scene, renderer, controls, bgTexture, bgWidth, bgHeight;
init();
animate();
function init() {
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(0, -4, -1.5);
loader = new THREE.TextureLoader();
loader.setCrossOrigin("");
scene = new THREE.Scene();
bgTexture = loader.load("https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/background.jpg",
function ( texture ) {
var img = texture.image;
bgWidth= img.width;
bgHeight = img.height;
resize();
}
);
scene.background = bgTexture;
bgTexture.wrapS = THREE.MirroredRepeatWrapping;
bgTexture.wrapT = THREE.MirroredRepeatWrapping;
scene.add(camera);
window.onresize = resize;
var ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.x = -0.75;
directionalLight.position.y = -0.5;
directionalLight.position.z = -1;
scene.add( directionalLight );
controls = new THREE.OrbitControls(camera, renderer.domElement);
createModel();
}
function createModel() {
var material = new THREE.MeshPhongMaterial({color:'#b090b0'});
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
}
function resize() {
var aspect = window.innerWidth / window.innerHeight;
var texAspect = bgWidth / bgHeight;
var relAspect = aspect / texAspect;
bgTexture.repeat = new THREE.Vector2( Math.max(relAspect, 1), Math.max(1/relAspect,1) );
bgTexture.offset = new THREE.Vector2( -Math.max(relAspect-1, 0)/2, -Math.max(1/relAspect-1, 0)/2 );
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = aspect;
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
})();
<script src="https://threejs.org/build/three.min.js"></script>
<!--script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js"></script-->
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>
thank you ))
I found yet another solution:
<!DOCTYPE html>
<head>
<title>three.js webgl - orbit controls</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #000;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
background-image:url(./foto.jpg);
margin: 0px;
overflow: hidden;
}
#info {
color:#000;
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
a {
color: red;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
three.js
</div>
<script src="./three.min.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<!--используем для вывода информации fps-->
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.z = 100;
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
scene = new THREE.Scene();
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader( manager );
loader.load( './kos.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load( './skull.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
object.position.y = 10;
scene.add( object );
} );
// lights
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( -1, -1, -1 );
scene.add( light );
light = new THREE.AmbientLight( 0xffffff );
scene.add( light );
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
}
function render() {
renderer.render( scene, camera );
stats.update();
}
</script>
</body>
It seems rather late in the day to be adding any contribution to this thread but here is my 'hap'orth':
<head>
<meta charset=utf-8>
<title>Temple7</title>
<style>
body { margin: 0;
}
canvas { width: 100%; height: 100%;
background-image:url(Clouds.jpg);
}
</style>
</head>
This rather simplistic approach has its limitations. The .jpg image retains its pixel dimensions so that, for different sizes of the browser window one sees different amounts of the image. If the canvas size exceeds the size of the .jpg, then tiling occurs.

Resources