Change vertice position on mousehover - javascript

I have a PlaneGeometry and I want to modify the z position of the vertice hovered but I don't know how to retrieve it.
//THREE.WebGLRenderer 69
// Generating plane
var geometryPlane = new THREE.PlaneGeometry( 100, 100, 20, 10 );
for (var vertIndex = 0; vertIndex < geometryPlane.vertices.length; vertIndex++) {
geometryPlane.vertices[vertIndex].z += Math.random();
}
geometryPlane.dynamic = true;
geometryPlane.computeFaceNormals();
geometryPlane.normalsNeedUpdate = true;
var materialPlane = new THREE.MeshLambertMaterial( {
color: 0xffff00,
side: THREE.DoubleSide,
shading: THREE.FlatShading,
overdraw: 0.5,
vertexColors: THREE.FaceColors
} );
plane = new THREE.Mesh( geometryPlane, materialPlane );
plane.geometry.colorsNeedUpdate = true;
// Mouse event
container[0].addEventListener( 'mousemove', onMouseMove, false );
function onMouseMove( event ) {
var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouseY = -( event.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouseX, mouseY, camera.near );
vector.unproject( camera );
raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
if ( intersects.length > 0 ) {
// Change the z position of the selected vertice
var selectedVertice = ???
selectedVertice.position.z +=5;
}
}

If the question concerns one vertex and not the whole object maybe you can :
1- retrieve the intersection face in intersects[0].face
2- this face may contain 3 vertices (it is probably a THREE.Face3) : find the nearest vertex V with the intersection point intersects[0].point.
3- change V.z
I don't know if it works : it is an idea... ;)

You can modify the Z position of the intersected object like this
intersects[0].object.position.z+=10;
You can refer to the code snippet below for demo/code.
var container, stats;
var camera, scene, raycaster, renderer;
var mouse = new THREE.Vector2(),
INTERSECTED;
var radius = 100,
theta = 0;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
var info = document.createElement('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js webgl - interactive cubes';
container.appendChild(info);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
scene = new THREE.Scene();
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 1, 1).normalize();
scene.add(light);
var geometry = new THREE.PlaneGeometry (50, 50, 50);
for (var i = 0; i < 500; i++) {
var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: Math.random() * 0xffffff
}));
object.position.x = Math.random() * 800 - 400;
object.position.y = Math.random() * 800 - 400;
object.position.z = Math.random() * 800 - 400;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = Math.random() + 0.5;
object.scale.y = Math.random() + 0.5;
object.scale.z = Math.random() + 0.5;
scene.add(object);
}
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
//
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
// find intersections
var vector = new THREE.Vector3(mouse.x, mouse.y, 1).unproject(camera);
raycaster.set(camera.position, vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
console.log(intersects[0].point);
console.log(intersects[0].object.position);
if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
/*******************************************************************/
/// You can change the Z position like the way done below
intersects[0].object.position.z+=10;
/********************************************************************/
INTERSECTED = intersects[0].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex(0xff0000);
}
} else {
if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
INTERSECTED = null;
}
renderer.render(scene, camera);
}
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.min.js"></script>

Related

THREE.js PlaneGeometry Converting a triangle drawing to a square

In the link below there is an animation created with triangles. How can I convert triangular areas into squares? A line runs through the middle when using "PlaneGeometry". When this line is deleted, the triangles turn into squares.
https://codepen.io/UIUXLab/pen/pBRzRZ
I want it like in the picture.
( function( $ ) {
"use strict";
$( function() {
var $window = $( window ),
windowWidth = window.innerWidth,
windowHeight = window.innerHeight,
rendererCanvasID = '3D-background-three-canvas5';
// Generate one plane geometries mesh to scene
//-------------------------------------
var camera,
scene,
material,
group,
lights = [],
renderer,
shaderSprite,
clock = new THREE.Clock();
var geometry, plane, simplex;
var factor = 300,
speed = 0.0005, // terrain size
cycle = 0, //move speed
scale = 30; // smoothness
init();
render();
function init() {
//camera
camera = new THREE.PerspectiveCamera( 60, windowWidth / windowHeight, 1, 10000 );
camera.position.set( 0, 0, 100 );
//Scene
scene = new THREE.Scene();
//HemisphereLight
lights[ 0 ] = new THREE.PointLight( 0xff0000, 1, 0 );
lights[ 1 ] = new THREE.PointLight( 0x0000ff, 1, 0 );
lights[ 2 ] = new THREE.PointLight( 0xffffff, 1, 0 );
lights[ 0 ].position.set( 0, 200, 0 );
lights[ 1 ].position.set( 100, 200, 100 );
lights[ 2 ].position.set( - 100, - 200, - 100 );
scene.add( lights[ 0 ] );
scene.add( lights[ 1 ] );
scene.add( lights[ 2 ] );
//WebGL Renderer
renderer = new THREE.WebGLRenderer( {
canvas : document.getElementById( rendererCanvasID ), //canvas
alpha : true,
antialias: true
} );
renderer.setSize( windowWidth, windowHeight );
// Immediately use the texture for material creation
group = new THREE.Object3D();
group.position.set(0,-300,-1000);
group.rotation.set(29.8,0,0);
geometry = new THREE.PlaneGeometry(4000, 2000, 128, 64);
material = new THREE.MeshLambertMaterial({
color: 0xffffff,
opacity: 1,
blending: THREE.NoBlending,
side: THREE.FrontSide,
transparent: false,
depthTest: false,
wireframe: true
});
plane = new THREE.Mesh(geometry, material);
plane.position.set(0, 0, 0);
simplex = new SimplexNoise();
moveNoise();
group.add(plane);
scene.add(group);
// Fires when the window changes
window.addEventListener( 'resize', onWindowResize, false );
}
function render() {
requestAnimationFrame( render );
var delta = clock.getDelta();
//To set a background color.
renderer.setClearColor( 0x000000 );
//change noise values over time
moveNoise();
//update sprite
cycle -= delta * 0.5;
renderer.render( scene, camera );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function moveNoise() {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = geometry.vertices[Symbol.iterator](), _step2; ! (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var vertex = _step2.value;
var xoff = vertex.x / factor;
var yoff = vertex.y / factor + cycle;
var rand = simplex.noise2D(xoff, yoff) * scale;
vertex.z = rand;
}
} catch(err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.
return != null) {
_iterator2.
return ();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
geometry.verticesNeedUpdate = true;
cycle += speed;
}
} );
} ) ( jQuery );
The middle line should disappear.
https://threejs.org/docs/#api/en/geometries/PlaneGeometry
You can change index of a plane geometry, and then use the geometry with LineSegments.
See this forum topic: Wireframe of quads
body{
overflow: hidden;
margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/three#0.136.0";
import {OrbitControls} from "https://cdn.skypack.dev/three#0.136.0/examples/jsm/controls/OrbitControls";
import { ImprovedNoise } from 'https://cdn.skypack.dev/three#0.136.0/examples/jsm/math/ImprovedNoise.js';
let perlin = new ImprovedNoise()
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 5, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", event => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
let controls = new OrbitControls(camera, renderer.domElement);
let g = new THREE.PlaneGeometry(20, 20, 50, 50);
let pos = g.attributes.position;
let uvs = g.attributes.uv;
let uv = new THREE.Vector2();
for(let i = 0; i < pos.count; i++){pos
uv.fromBufferAttribute(uvs, i);
uv.multiplyScalar(5);
let z = perlin.noise(uv.x, uv.y, 0) * 3;
pos.setZ(i, z);
}
g.rotateX(-Math.PI * 0.5);
ToQuads(g); // change the index
let m = new THREE.LineBasicMaterial({color: "magenta"});
let o = new THREE.LineSegments(g, m);
scene.add(o);
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
function ToQuads(g) {
let p = g.parameters;
let segmentsX = (g.type == "TorusBufferGeometry" ? p.tubularSegments : p.radialSegments) || p.widthSegments || p.thetaSegments || (p.points.length - 1) || 1;
let segmentsY = (g.type == "TorusBufferGeometry" ? p.radialSegments : p.tubularSegments) || p.heightSegments || p.phiSegments || p.segments || 1;
let indices = [];
for (let i = 0; i < segmentsY + 1; i++) {
let index11 = 0;
let index12 = 0;
for (let j = 0; j < segmentsX; j++) {
index11 = (segmentsX + 1) * i + j;
index12 = index11 + 1;
let index21 = index11;
let index22 = index11 + (segmentsX + 1);
indices.push(index11, index12);
if (index22 < ((segmentsX + 1) * (segmentsY + 1) - 1)) {
indices.push(index21, index22);
}
}
if ((index12 + segmentsX + 1) <= ((segmentsX + 1) * (segmentsY + 1) - 1)) {
indices.push(index12, index12 + segmentsX + 1);
}
}
g.setIndex(indices);
}
</script>

How to zoom a three.js scene with the mouse wheel?

I have a simple three.js graphics, and I tried to use the answers in this and this question to make the created plot zoomable by the mouse wheel. By using the mouse wheel I would like to zoom in to the graphics or to zoom out.
Here is the complete code: pastebin link
However, when turning the mouse wheel nothing happens, and I do not get an error message. Maybe I am missing something?
DEMO
var container, camera, scene, renderer, colors;
var selected = 0;
var selectedObject;
var objects = [];
// DOM element...
container = document.createElement('div');
document.body.appendChild(container);
// Camera...
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 150);
// Scene...
scene = new THREE.Scene();
scene.add(camera);
// Renderer...
renderer = new THREE.WebGLRenderer({
clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);
// Scatter plot...
scatterPlot = new THREE.Object3D();
scene.add(scatterPlot);
// Plot some random points...
circle = new THREE.CircleGeometry(1, 20);
colors = [];
var max = 50;
var min = -50;
for (var i = 0; i < 10; i++) {
var object = new THREE.Mesh( circle.clone(), new THREE.MeshBasicMaterial( { color: new THREE.Color('black'), opacity: 0.5 } ) );
object.position.x = Math.random() * (max - min) + min;
object.position.y = Math.random() * (max - min) + min;
object.position.z = 0;
scene.add( object );
objects.push( object );
}
animate();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
//intersects[ 0 ].object.material.color.set('red');
//intersects[ 0 ].object.geometry.scale(1.1,1.1,1.1);
if (selected === 0) {
selected = 1;
selectedObject = intersects[ 0 ].object;
selectedObject.material.color.set('red');
console.log(selectedObject.position.x);
} else {
selected = 0;
var geometry = new THREE.Geometry();
geometry.vertices.push(intersects[ 0 ].object.position);
geometry.vertices.push(selectedObject.position);
var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0x0000ff }));
scene.add(line);
selectedObject.material.color.set('black');
}
}
}
function onWindowResize() {
camera.left = window.innerWidth / - 2;
camera.right = window.innerWidth / 2;
camera.top = window.innerHeight / 2;
camera.bottom = window.innerHeight / - 2;
camera.aspect = window.innerWidth / window.innerHeight;
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseWheel( event ) {
var fovMAX = 160;
var fovMIN = 1;
camera.fov -= event.wheelDeltaY * 0.05;
camera.fov = Math.max( Math.min( camera.fov, fovMAX ), fovMIN );
camera.projectionMatrix = new THREE.Matrix4().makePerspective(camera.fov, window.innerWidth / window.innerHeight, camera.near, camera.far);
}
body { margin: 0; }
canvas { width: 100%; height: 100% }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/54/three.js"></script>
In your code add event listener
document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
document.addEventListener( 'mousewheel', (event) => {
camera.position.z +=event.deltaY/500;
});
The mousewheel event is supported only in Webkit browsers.
For cross-browser compaitibility use the wheel event.

How to set up image background in three.js?

I am trying to set up image background for my scene with globe in three.js, but unfortunately, when I did it the main object of my scene also became black (the same colour with background.
I used method:
renderer = new THREE.WebGLRenderer({ antialias: false, alpha:true });
Which makes default background transparent. And then I added image-background in CSS part.
My whole script for the scene looks like this:
var container, stats;
var camera, scene, renderer;
var group;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
//closer
camera.position.z = 500;
scene = new THREE.Scene();
group = new THREE.Group();
scene.add( group );
// earth
var loader = new THREE.TextureLoader();
loader.load( 'textures/mapnew1.jpg', function ( texture ) {
var geometry = new THREE.SphereGeometry( 180, 32, 32 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
group.add( mesh );
} );
// shadow
var canvas = document.createElement( 'canvas' );
canvas.width = 128;
canvas.height = 128;
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.1, '#000000' );
gradient.addColorStop( 1, '#000000' );
context.fillStyle = gradient;
context.fillRect( 0, 0, canvas.width, canvas.height );
var texture = new THREE.CanvasTexture( canvas );
var geometry = new THREE.PlaneBufferGeometry( 300, 300, 3, 3 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.y = - 200;
mesh.rotation.x = - Math.PI / 2;
group.add( mesh );
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer = new THREE.WebGLRenderer({ antialias: false, alpha:true });
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000, 0);
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.08;
camera.position.y += ( - mouseY - camera.position.y ) * 0.08;
camera.lookAt( scene.position );
group.rotation.y -= 0.003;
renderer.render( scene, camera );
}
</script>
This is my CSS:
body {
color: #ffffff;
font-family:'Futura';
font-size:20px;
text-align: center;
background-image: url(textures/starfield.png);
background-color: black;
margin: 0px;
overflow: hidden;
}
Do you have any ideas how to fix it and make globe visible?
Thank you very much!
Regarding the background image, you are setting the alpha value for WebGLRenderer, which is correct. You didn't post your CSS, but ensure you're setting the background image on your container, not on the canvas.
Also, comment out this line:
renderer.setClearColor(0x000000, 0);
You don't need to set a clear color, since you are clearing to transparency, not a color. That should resolve the background image issue.
Regarding the all-black model, you need a light in your scene. Try adding this to your init method:
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
This will add a light source at the location of your camera (and will follow the camera as it moves).
Edit to add snippet:
var container, stats;
var camera, scene, renderer;
var group;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.getElementById('container');
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
//closer
camera.position.z = 500;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
scene = new THREE.Scene();
group = new THREE.Group();
scene.add(group);
// earth
var loader = new THREE.TextureLoader();
loader.crossOrigin = '';
loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Equirectangular_projection_SW.jpg/640px-Equirectangular_projection_SW.jpg', function(texture) {
var geometry = new THREE.SphereGeometry(180, 32, 32);
var material = new THREE.MeshBasicMaterial({
map: texture,
overdraw: 0.5
});
var mesh = new THREE.Mesh(geometry, material);
group.add(mesh);
});
// shadow
var canvas = document.createElement('canvas');
canvas.width = 128;
canvas.height = 128;
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.1, '#000000');
gradient.addColorStop(1, '#000000');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
var texture = new THREE.CanvasTexture(canvas);
var geometry = new THREE.PlaneBufferGeometry(300, 300, 3, 3);
var material = new THREE.MeshBasicMaterial({
map: texture,
overdraw: 0.5
});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.y = -200;
mesh.rotation.x = -Math.PI / 2;
group.add(mesh);
renderer = new THREE.WebGLRenderer({
antialias: false,
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
//renderer.setClearColor(0x000000, 0);
container.appendChild(renderer.domElement);
stats = new Stats();
container.appendChild(stats.dom);
document.addEventListener('mousemove', onDocumentMouseMove, false);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
//
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.08;
camera.position.y += (-mouseY - camera.position.y) * 0.08;
camera.lookAt(scene.position);
group.rotation.y -= 0.003;
renderer.render(scene, camera);
}
body {
color: #ffffff;
font-family: 'Futura';
font-size: 20px;
text-align: center;
background-image: url(https://upload.wikimedia.org/wikipedia/commons/6/62/Starsinthesky.jpg);
background-color: black;
margin: 0px;
overflow: hidden;
}
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/renderers/Projector.js"></script>
<script src="https://threejs.org/examples/js/libs/stats.min.js"></script>
<div id="container"></div>
three.js r86
Since a while, there is:
var texture = new THREE.TextureLoader().load( "textures/bg.jpg" );
scene.background = texture;
I'm using three.js v 0.87
There are two ways to do it
1) Load a image using TextureLoader and set it as background. This will result into static background which may not look very realistic.
var texture = new THREE.TextureLoader().load(
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
);
scene.background = texture;
2) Use skybox to load images for top, left, right bottom, front back sides. Then set them inside a cube or sphere geometry
var urls = [
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
"https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg"
];
var materialArray = [];
for (var i = 0; i < 6; i++)
materialArray.push(
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load(urls[i]),
side: THREE.BackSide
})
);
var skyGeometry = new THREE.SphereGeometry(400, 32, 32);
var skyMaterial = new THREE.MeshFaceMaterial(materialArray);
var skybox = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(skybox);
This will give a sphere with images as texture on backside. Just replace THREE.SphereGeometry with THREE.CubeGeometry and you can emulate envMap.
The previous solutions didn't work for me,
they miss the using of callback so at least from v.0.124 of the library,
this is how you can set the background image for the scene:
var texture_bg = new THREE.TextureLoader().load("img/bg.jpg", () => {
scene.background = texture_bg;
});

Multiple moving objects with text attached to each object

I've been playing with the interactive cubes and decided to add a click function, which leads to a specific link. Now I would like to add unique text on each block which is rendered as a material. For right now, I am using a single material, so I am thinking I need to create an array for all my possible materials, however whenever I reference that array in the parameters for building the mesh of my objects, I get a setHex() is undefined returned to me in the console. How can I attach a unique material to each cube?
<html lang="en">
<head>
<title>three.js webgl - interactive cubes</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: #f0f0f0;
margin: 0px;
overflow: hidden;
}
div#stats{
display:none;
}
p{
position:absolute;
top:500px;
left:500px;
}
</style>
</head>
<body>
<div><p>Hello!</p></div>
<script src="../build/three.min.js"></script>
<script src="js/renderers/Projector.js"></script>
<script src='../build/threex.dynamictexture.js'></script>
<script src="js/libs/stats.min.js"></script>
<script>
var container, stats;
var camera, scene, raycaster, renderer;
var mouse = new THREE.Vector2(), INTERSECTED;
var radius = 100, theta = 0;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
// info.innerHTML = 'three.js webgl - interactive cubes';
container.appendChild( info );
camera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 1, 10000 );
scene = new THREE.Scene();
var light = new THREE.DirectionalLight( 0x6699CC, 0.5 );
light.position.set( 1, 1, 1 ).normalize();
scene.add( light );
raycaster = new THREE.Raycaster();
projector = new THREE.Projector();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
var dynamicTexture = new THREEx.DynamicTexture(512,512);
var dynamicTexture2 = new THREEx.DynamicTexture(512,512);
dynamicTexture.context.font = "bold"+(0.2*512)+ "px Courier";
dynamicTexture.texture.anisotropy = renderer.getMaxAnisotropy();
dynamicTexture2.context.font = "bold"+(0.2*512)+ "px Courier";
dynamicTexture2.texture.anisotropy = renderer.getMaxAnisotropy();
dynamicTexture2.clear('blue');
dynamicTexture.drawTextCooked({
text: 'alltheletters',
lineHeight: 0.2,
})
dynamicTexture.clear('gray');
dynamicTexture.drawTextCooked({
text: 'wow text text text',
lineHeight: 0.2,
})
// var materialArray = [];
// materialArray.push(new THREE.MeshBasicMaterial({map: dynamicTexture2 }))
scene.add(object);
for ( var i = 0; i < 5; i ++ ) {
var object = new THREE.Mesh( geometry, material );
object.position.x = Math.random() * 800 - 400;
object.position.y = Math.random() * 800 - 400;
object.position.z = Math.random() * 800 - 400;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = Math.random() + 0.5;
object.scale.y = Math.random() + 0.5;
object.scale.z = Math.random() + 0.5;
scene.add( object );
var geometry = new THREE.BoxGeometry( 62, 62, 62 );
var material = new THREE.MeshBasicMaterial({
map: dynamicTexture.texture,
color:Math.random() * 0xffffff,
name: "box1",
})
switch (i) {
case 0:
object.userData = {
URL: "http://google.com"
};
break;
case 1:
object.userData = {
URL: "http://yahoo.com"
};
break;
case 2:
object.userData = {
URL: "http://msn.com"
};
break;
case 3:
object.userData = {
URL: "http://engadget.com"
};
break;
case 4:
object.userData = {
URL: "http://stackoverflow.com"
};
break;
}
}
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
document.addEventListener('mousedown', onDocumentMouseDown,false);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
function onDocumentMouseDown(event) {
event.preventDefault();
var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 -
1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position)
.normalize());
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
window.open(intersects[0].object.userData.URL);
}
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
theta += 0.1;
camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
camera.lookAt( scene.position );
camera.updateMatrixWorld();
// find intersections
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( scene.children ), material;
// for(var p =0; p < intersects.length; p++){
// }
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
if (INTERSECTED){
material = INTERSECTED.material;
if(material.emissive){
material.emissive.setHex(INTERSECTED.currentHex);
}
else{
material.color.setHex(INTERSECTED.currentHex);
}
}
INTERSECTED = intersects[0].object;
material = INTERSECTED.material;
if(material.emissive){
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
material.emissive.setHex(0xff0000);
}
else{
INTERSECTED.currentHex = material.color.getHex();
material.color.setHex(0xff0000);
}
console.log(INTERSECTED.position);
}
}
else {
if (INTERSECTED){
material = INTERSECTED.material;
if(material.emissive){
material.emissive.setHex(INTERSECTED.currentHex);
}
else
{
material.color.setHex(INTERSECTED.currentHex);
}
}
INTERSECTED = null;
}
renderer.render( scene, camera );
}
</script>
</body>
</html>
I don't think the problem is the array, its the object in the array. Try this:
var materialArray = [];
materialArray.push(new THREE.MeshBasicMaterial({
map: dynamicTexture2.texture,
color:Math.random() * 0xffffff,
name: "box1",
}));
//...
var object = new THREE.Mesh( geometry, materialArray[0] );
If you want to create multiple cubes with different materials, you'll need to create multiple objects, instead of reusing object. You can wrap all the object creation/positioning code in a function, and have the unique material be a parameter.

How do I add a tag/label to appear on top of several objects so that the tag always faces the camera when the user clicks the object?

Essentially, what I am saying is I want to create a tag or label that appears on top of/on the surface of an object so that the tag always faces the camera when the user clicks the object even when the object is rotated.
How do I go about doing so?
I was told to use Orthogonal camera (but I'm not sure how?) and CSS for the label (see previous post: How can I make my text labels face the camera at all times? Perhaps using sprites?)
The label in CSS and html is below. However, I want to do this for several objects as well, so I guess I can make a list of all the tags I want for each cube in this case.
CSS:
label {
vertical-align: middle;
display: table-cell;
background-color : #99FFCC;
border: 1px solid #008000;
width: 150px;
}
HTML:
<div id="Cube1">
<label>Cube 1</label>
</div>
Previous Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js canvas - interactive - cubes</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: #f0f0f0;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="js/three.min.js"></script>
<script src="js/stats.min.js"></script>
<script>
var container, stats;
var camera, scene, projector, renderer;
var projector, mouse = { x: 0, y: 0 }, INTERSECTED;
var particleMaterial;
var currentLabel = null;
var objects = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js - clickable objects';
container.appendChild( info );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 0, 300, 500 );
scene = new THREE.Scene();
var geometry = new THREE.CubeGeometry( 100, 100, 100 );
for ( var i = 0; i < 10; i ++ ) {
var object = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, opacity: 0.5 } ) );
object.position.x = Math.random() * 800 - 400;
object.position.y = Math.random() * 800 - 400;
object.position.z = Math.random() * 800 - 400;
object.scale.x = Math.random() * 2 + 1;
object.scale.y = Math.random() * 2 + 1;
object.scale.z = Math.random() * 2 + 1;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.label = "Object " + i;
scene.add( object );
objects.push( object );
}
var PI2 = Math.PI * 2;
particleMaterial = new THREE.ParticleCanvasMaterial( {
color: 0x000000,
program: function ( context ) {
context.beginPath();
context.arc( 0, 0, 1, 0, PI2, true );
context.closePath();
context.fill();
}
} );
projector = new THREE.Projector();
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
if ( intersects[ 0 ].object != INTERSECTED )
{
// restore previous intersection object (if it exists) to its original color
if ( INTERSECTED ) {
INTERSECTED.material.color.setHex( INTERSECTED.currentHex ); }
// store reference to closest object as current intersection object
INTERSECTED = intersects[ 0 ].object;
// store color of closest object (for later restoration)
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
// set a new color for closest object
INTERSECTED.material.color.setHex( 0xffff00 );
var canvas1 = document.createElement('canvas');
var context1 = canvas1.getContext('2d');
context1.font = "Bold 40px Arial";
context1.fillStyle = "rgba(255,0,0,0.95)";
context1.fillText(INTERSECTED.label, 0, 50);
// canvas contents will be used for a texture
var texture1 = new THREE.Texture(canvas1)
texture1.needsUpdate = true;
var material1 = new THREE.MeshBasicMaterial( {map: texture1, side:THREE.DoubleSide } );
material1.transparent = true;
var mesh1 = new THREE.Mesh(
new THREE.PlaneGeometry(canvas1.width, canvas1.height),
material1
);
mesh1.position = intersects[0].point;
if (currentLabel)
scene.remove(currentLabel);
scene.add( mesh1 );
currentLabel = mesh1;
}
else // there are no intersections
{
// restore previous intersection object (if it exists) to its original color
if ( INTERSECTED ) {
console.log("hello");
INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
}
// remove previous intersection object reference
// by setting current intersection object to "nothing"
INTERSECTED = null;
mesh1 = null;
mesh1.position = intersects[0].point;
scene.add( mesh1 );
}
//var particle = new THREE.Particle( particleMaterial );
//particle.position = intersects[ 0 ].point;
//particle.scale.x = particle.scale.y = 8;
//scene.add( particle );
}
/*
// Parse all the faces
for ( var i in intersects ) {
intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 );
}
*/
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
var radius = 600;
var theta = 0;
function render() {
theta += 0.1;
camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>
Please let me know if I'm being unclear.
I'm not especially familiar with Three.js, but here's the usual steps:
Choose a point on the surface of your object you want to align the label to.
Use projector.projectVector to get an on-screen point from the in-world point.
(You may need to scale the result from NDC (-1 to 1) to canvas (0 to canvas.width) coordinates here; I'm not sure.)
Use the X and Y to set CSS absolute positioning for your label.
Here's code I wrote to do the same thing in my Cubes project (not using Three.js, but the principles are the same). It is slightly more complex because what it does is position the element so that it is next to an object represented by a set of points (which are provided to the callback passed to pointGenerator). It also tries to do sensible things when the object is out of view of the camera.
Feel free to reuse this code and adapt it to your liking.
// Position an overlay HTML element adjacent to the provided set of points.
function positionByWorld(element, keepInBounds, pointGenerator) {
var canvasStyle = window.getComputedStyle(theCanvas,null);
var canvasWidth = parseInt(canvasStyle.width, 10);
var canvasHeight = parseInt(canvasStyle.height, 10);
var elemStyle = window.getComputedStyle(element, null);
var elemWidth = parseInt(elemStyle.width, 10);
var elemHeight = parseInt(elemStyle.height, 10);
var slx = Infinity;
var sly = Infinity;
var shx = -Infinity;
var shy = -Infinity;
var toScreenPoint = vec4.create();
pointGenerator(function (x, y, z, w) {
toScreenPoint[0] = x;
toScreenPoint[1] = y;
toScreenPoint[2] = z;
toScreenPoint[3] = w;
renderer.transformPoint(toScreenPoint);
toScreenPoint[0] /= toScreenPoint[3];
toScreenPoint[1] /= toScreenPoint[3];
toScreenPoint[2] /= toScreenPoint[3];
if (toScreenPoint[3] > 0) {
slx = Math.min(slx, toScreenPoint[0]);
shx = Math.max(shx, toScreenPoint[0]);
sly = Math.min(sly, toScreenPoint[1]);
shy = Math.max(shy, toScreenPoint[1]);
}
});
if (shx > -1 && shy > -1 && slx < 1 && sly < 1 /* visible */) {
// convert to screen
slx = (slx + 1) / 2 * canvasWidth;
//shx = (shx + 1) / 2 * canvasWidth;
//sly = (sly + 1) / 2 * canvasHeight;
shy = (shy + 1) / 2 * canvasHeight;
if (keepInBounds) {
slx = Math.max(0, Math.min(canvasWidth - elemWidth, slx));
shy = Math.max(0, Math.min(canvasHeight - elemHeight, shy));
}
element.style.left = slx + "px";
element.style.bottom = shy + "px";
} else {
element.style.left = canvasWidth + "px";
}
}
—Permalink on GitHub

Categories