this could be a duplicate, but I have not found anything as yet.
I am trying to create tooltip for on mouse hover. (perspective camera)
Tooltip issue:
https://jsfiddle.net/thehui87/d12fLr0b/14/
threejs r76
function onDocumentMouseMove( event )
{
// update sprite position
// sprite1.position.set( event.clientX, event.clientY, 1 );
// update the mouse variable
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouse.x, mouse.y, 0 );
vector.unproject(camera);
var dir = vector.sub( camera.position ).normalize();
var distance = - camera.position.z / dir.z;
var pos = camera.position.clone().add( dir.multiplyScalar( distance ) );
sprite1.position.copy(pos);
}
But once i orbit the camera the tooltip moves away.
References for tooltip.
http://stemkoski.github.io/Three.js/Mouse-Tooltip.html
Three.js - Object follow mouse position
If anyone could kindly point me to the right answer on stackoverflow or provide an alternate solution.
Thanks
Well working tooltip is not only correctly placed text label. It has some of show and hide intelligence.
It should:
not appear immediately, but once mouse becomes stationary over some object,
not disappear immediately, rather it should fade away after mouse left the object area,
it should neither follow the mouse, nor stay where it was, if user moves the mouse around the object area not leaving it.
All of that is included in my solution: http://jsfiddle.net/mmalex/ycnh0wze/
<div id="tooltip"></div> must be initially added to HTML. The recommended CSS you find below. Crucial to have it position: fixed;, anything else is a matter of taste.
#tooltip {
position: fixed;
left: 0;
top: 0;
min-width: 100px;
text-align: center;
padding: 5px 12px;
font-family: monospace;
background: #a0c020;
display: none;
opacity: 0;
border: 1px solid black;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.5);
transition: opacity 0.25s linear;
border-radius: 3px;
}
var scene = new THREE.Scene();
var raycaster = new THREE.Raycaster();
//create some camera
camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.x = 5;
camera.position.y = 5;
camera.position.z = 5;
camera.lookAt(0, 0, 0);
var controls = new THREE.OrbitControls(camera);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color(0x595959));
document.body.appendChild(renderer.domElement);
// white spotlight shining from the side, casting a shadow
var spotLight = new THREE.SpotLight(0xffffff, 2.5, 25, Math.PI / 6);
spotLight.position.set(4, 10, 7);
scene.add(spotLight);
// collect objects for raycasting,
// for better performance don't raytrace all scene
var tooltipEnabledObjects = [];
var colors = new RayysWebColors();
for (let k = 0; k < 12; k++) {
var size = 0.5;
var geometry = new THREE.BoxGeometry(size, 0.2, size);
var randomColor = colors.pickRandom();
var material = new THREE.MeshPhongMaterial({
color: randomColor.hex,
transparent: true,
opacity: 0.75
});
var cube = new THREE.Mesh(geometry, material);
cube.userData.tooltipText = randomColor.name;
cube.applyMatrix(new THREE.Matrix4().makeTranslation(-3 + 6 * Math.random(), 0, -3 + 0.5 * k));
scene.add(cube);
tooltipEnabledObjects.push(cube);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
};
// this will be 2D coordinates of the current mouse position, [0,0] is middle of the screen.
var mouse = new THREE.Vector2();
var latestMouseProjection; // this is the latest projection of the mouse on object (i.e. intersection with ray)
var hoveredObj; // this objects is hovered at the moment
// tooltip will not appear immediately. If object was hovered shortly,
// - the timer will be canceled and tooltip will not appear at all.
var tooltipDisplayTimeout;
// This will move tooltip to the current mouse position and show it by timer.
function showTooltip() {
var divElement = $("#tooltip");
if (divElement && latestMouseProjection) {
divElement.css({
display: "block",
opacity: 0.0
});
var canvasHalfWidth = renderer.domElement.offsetWidth / 2;
var canvasHalfHeight = renderer.domElement.offsetHeight / 2;
var tooltipPosition = latestMouseProjection.clone().project(camera);
tooltipPosition.x = (tooltipPosition.x * canvasHalfWidth) + canvasHalfWidth + renderer.domElement.offsetLeft;
tooltipPosition.y = -(tooltipPosition.y * canvasHalfHeight) + canvasHalfHeight + renderer.domElement.offsetTop;
var tootipWidth = divElement[0].offsetWidth;
var tootipHeight = divElement[0].offsetHeight;
divElement.css({
left: `${tooltipPosition.x - tootipWidth/2}px`,
top: `${tooltipPosition.y - tootipHeight - 5}px`
});
// var position = new THREE.Vector3();
// var quaternion = new THREE.Quaternion();
// var scale = new THREE.Vector3();
// hoveredObj.matrix.decompose(position, quaternion, scale);
divElement.text(hoveredObj.userData.tooltipText);
setTimeout(function() {
divElement.css({
opacity: 1.0
});
}, 25);
}
}
// This will immediately hide tooltip.
function hideTooltip() {
var divElement = $("#tooltip");
if (divElement) {
divElement.css({
display: "none"
});
}
}
// Following two functions will convert mouse coordinates
// from screen to three.js system (where [0,0] is in the middle of the screen)
function updateMouseCoords(event, coordsObj) {
coordsObj.x = ((event.clientX - renderer.domElement.offsetLeft + 0.5) / window.innerWidth) * 2 - 1;
coordsObj.y = -((event.clientY - renderer.domElement.offsetTop + 0.5) / window.innerHeight) * 2 + 1;
}
function handleManipulationUpdate() {
raycaster.setFromCamera(mouse, camera); {
var intersects = raycaster.intersectObjects(tooltipEnabledObjects);
if (intersects.length > 0) {
latestMouseProjection = intersects[0].point;
hoveredObj = intersects[0].object;
}
}
if (tooltipDisplayTimeout || !latestMouseProjection) {
clearTimeout(tooltipDisplayTimeout);
tooltipDisplayTimeout = undefined;
hideTooltip();
}
if (!tooltipDisplayTimeout && latestMouseProjection) {
tooltipDisplayTimeout = setTimeout(function() {
tooltipDisplayTimeout = undefined;
showTooltip();
}, 330);
}
}
function onMouseMove(event) {
updateMouseCoords(event, mouse);
latestMouseProjection = undefined;
hoveredObj = undefined;
handleManipulationUpdate();
}
window.addEventListener('mousemove', onMouseMove, false);
animate();
Replace:
var vector = new THREE.Vector3( mouse.x, mouse.y, 0 );
by:
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
Related
I want something like this:
https://drive.google.com/file/d/1v_4M59Ny93QwT52unfM9N_tfzo3xRAq1/view?usp=share_link
This is my code
<!DOCTYPE html>
<html>
<head>
<title>Three.js JPG Background with Custom Position</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js"></script>
<script src="./js/tween.js/dist/tween.umd.js"></script>
<!-- Css -->
<style>
body {
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>
<script>
// Initialize Three.js scene
var scene = new THREE.Scene();
var camera = new THREE.OrthographicCamera(window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 0.1,);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Load the Main BG texture
var mainBg = new THREE.TextureLoader().load("http://127.0.0.1:5500/img/main-bg.jpg");
// Create a full-screen plane to display the texture
var geometry1 = new THREE.PlaneGeometry(window.innerWidth, window.innerHeight);
var material1 = new THREE.MeshBasicMaterial({ map: mainBg });
var plane1 = new THREE.Mesh(geometry1, material1);
plane1.position.set(0, 0, 0)
scene.add(plane1);
// Create a full-screen plane to display the texture
var frame1 = new THREE.TextureLoader().load("http://127.0.0.1:5500/img/frame1.png");
var geometry2 = new THREE.PlaneGeometry(90, 110);
var material2 = new THREE.MeshBasicMaterial({ map: frame1 });
var plane2 = new THREE.Mesh(geometry2, material2);
plane2.position.set(-190, 130, .1);
scene.add(plane2);
// Check if mouse is over the child asset
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var zoomed = false;
// Mouse move function
function onMouseMove(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([plane2]);
if (intersects.length > 0 && !zoomed) {
zoomed = true;
camera.position.set(plane2.position.x, plane2.position.y, plane2.position.z);
camera.lookAt(plane2.position.x, plane2.position.y, plane2.position.z);
} else if (intersects.length === 0 && zoomed) {
zoomed = false;
camera.position.set(0, 0, 5);
camera.lookAt(new THREE.Vector3(0, 0, 0));
}
}
// Mouse move function calling on moving mouse
document.addEventListener('mousemove', onMouseMove, false);
window.addEventListener('mousedown', function () {
gsap.to(camera.position, {
z: 15,
duration: 15
});
})
// Render loop
function render() {
camera.position.z = 5;
requestAnimationFrame(render);
renderer.render(scene, camera);
}
render();
</script>
</body>
</html>
assets:
frame1
and
main-bg
i made frame 1 on the center of the screen by hovering it but cannot make camera to zoom in on it. I tried tween but I think there is something wrong in the basics of my code
Sorry i am new to this and this is my first threejs project
You can apply a mousemove event on the canvas and use event.clientX or event.clientY to read live mouse pointer values. These values can then be used within the the listener to update values of camera.position.z to change zoom.
How can I have an ThreeJS object rotate on an axis that is at angle.
Like from this codepen I made, the left square rotates on its center and moved up when you click on the "rotate up" button.
I want the left cure rotate along the red axis in the image attached and move along on that axis when click on the "Rotate 45 degree" button. I can make up move along the axis, but the rotation is wrong. How can I make the cute rotate along the red axis?
****EDIT:
PS: Sorry I cannot get the snippet working here. Please use the codepen link for the demo.
https://codepen.io/eforblue/pen/MWpYggY
var upTl = gsap.timeline();
var degreeTl = gsap.timeline();
var width = window.innerWidth;
var height = window.innerHeight;
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
var scene = new THREE.Scene();
var cubeGeometry = new THREE.CubeGeometry(100, 100, 100);
var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
scene.add(cube);
var cube2 = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube2.position.set(200, 200, 0);
cube2.rotation.z = 45;
scene.add(cube2);
var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);
camera.position.set(0, 500, 3000);
camera.lookAt(cube.position);
scene.add(camera);
var skyboxGeometry = new THREE.CubeGeometry(100, 100, 100);
var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0, 300, 200);
scene.add(pointLight);
var clock = new THREE.Clock();
function render() {
requestAnimationFrame(render);
// cube.rotation.y -= clock.getDelta();
renderer.render(scene, camera);
}
render();
$('.up').on('click', () => {
console.log('click')
upTl.to( cube.rotation, 1, { y: Math.PI * 3 }, 0 )
.to( cube.position, 1, { y: cube.position.y + 400 }, 0 )
})
$('.degree').on('click', () => {
degreeTl.to( cube2.rotation, 1, { y: Math.PI * 3 }, 0 )
.to( cube2.position, 1, { x: cube2.position.x + 300, y:cube2.position.y + 300 }, 0 )
});
canvas {
position: fixed;
top: 0;
left: 0;
}
button {
position:relative;
z-index: 99;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="./main.js"></script>
<button class="up">rotate up</button>
<button class="degree">rotate 45deg</button>
In your case it's easier to use quaternions to rotate around your red axis, you can use the following function and define your rotation axis in the "axis" parameter.
static rotateAroundWorldAxis(mesh, point, axis, angle) {
const q = new Quaternion();
q.setFromAxisAngle(axis, angle);
mesh.applyQuaternion(q);
mesh.position.sub(point);
mesh.position.applyQuaternion(q);
mesh.position.add(point);
return mesh;
}
is there some helper method in THREE.js that allows one to see the number assigned to each vertex in a mesh loaded from an obj file? [minimal obj file]
I'm trying to rig up some bones inside a mesh, and want to position those bones between particular vertices, but don't know the vertex numbers yet. A little tool like this could be super helpful for this purpose.
If there's no such method in THREE.js, I'll likely build a tool to this effect, but I wanted to save the time if I can. Any suggestions on where to look in THREE.js for this functionality would be greatly appreciated!
The solution is:
Place small boxes on each vertex,
Add tooltip to each box,
Tooltip text set to vertex index.
How to add tooltip in three.js find in my answer here: Threejs Tooltip
Working jsfiddle for your convenience find here: http://jsfiddle.net/mmalex/fux6srgv/
Javascript code:
var scene = new THREE.Scene();
var raycaster = new THREE.Raycaster();
//create some camera
camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.x = 3;
camera.position.y = 3;
camera.position.z = 3;
camera.lookAt(0, 0, 0);
var controls = new THREE.OrbitControls(camera);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color(0x595959));
document.body.appendChild(renderer.domElement);
// white spotlight shining from the side, casting a shadow
var spotLight = new THREE.SpotLight(0xffffff, 2.5, 25, Math.PI / 6);
spotLight.position.set(4, 10, 7);
scene.add(spotLight);
// collect objects for raycasting,
// for better performance don't raytrace all scene
var tooltipEnabledObjects = [];
var colors = new RayysWebColors();
var dodecahedronGeometry = new THREE.DodecahedronBufferGeometry(1, 0);
var dodecahedronMaterial = new THREE.MeshPhongMaterial({
color: colors.pickRandom().hex,
transparent: true,
opacity: 0.75
});
var dodecahedron = new THREE.Mesh(dodecahedronGeometry, dodecahedronMaterial);
scene.add(dodecahedron);
var size = 0.1;
var vertGeometry = new THREE.BoxGeometry(size, size, size);
var vertMaterial = new THREE.MeshBasicMaterial({
color: 0x0000ff,
transparent: false
});
var verts = dodecahedronGeometry.attributes.position.array;
for (let k=0; k<verts.length; k+=3) {
var vertMarker = new THREE.Mesh(vertGeometry, vertMaterial);
// this is how tooltip text is defined for each box
let tooltipText = `idx: ${k}, pos: [${verts[k].toFixed(3)},${verts[k+1].toFixed(3)},${verts[k+2].toFixed(3)}]`;
vertMarker.userData.tooltipText = tooltipText;
vertMarker.applyMatrix(new THREE.Matrix4().makeTranslation(verts[k],verts[k+1],verts[k+2]));
scene.add(vertMarker);
tooltipEnabledObjects.push(vertMarker);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
};
// this will be 2D coordinates of the current mouse position, [0,0] is middle of the screen.
var mouse = new THREE.Vector2();
var latestMouseProjection; // this is the latest projection of the mouse on object (i.e. intersection with ray)
var hoveredObj; // this objects is hovered at the moment
// tooltip will not appear immediately. If object was hovered shortly,
// - the timer will be canceled and tooltip will not appear at all.
var tooltipDisplayTimeout;
// This will move tooltip to the current mouse position and show it by timer.
function showTooltip() {
var divElement = $("#tooltip");
if (divElement && latestMouseProjection) {
divElement.css({
display: "block",
opacity: 0.0
});
var canvasHalfWidth = renderer.domElement.offsetWidth / 2;
var canvasHalfHeight = renderer.domElement.offsetHeight / 2;
var tooltipPosition = latestMouseProjection.clone().project(camera);
tooltipPosition.x = (tooltipPosition.x * canvasHalfWidth) + canvasHalfWidth + renderer.domElement.offsetLeft;
tooltipPosition.y = -(tooltipPosition.y * canvasHalfHeight) + canvasHalfHeight + renderer.domElement.offsetTop;
var tootipWidth = divElement[0].offsetWidth;
var tootipHeight = divElement[0].offsetHeight;
divElement.css({
left: `${tooltipPosition.x - tootipWidth/2}px`,
top: `${tooltipPosition.y - tootipHeight - 5}px`
});
// var position = new THREE.Vector3();
// var quaternion = new THREE.Quaternion();
// var scale = new THREE.Vector3();
// hoveredObj.matrix.decompose(position, quaternion, scale);
divElement.text(hoveredObj.userData.tooltipText);
setTimeout(function() {
divElement.css({
opacity: 1.0
});
}, 25);
}
}
// This will immediately hide tooltip.
function hideTooltip() {
var divElement = $("#tooltip");
if (divElement) {
divElement.css({
display: "none"
});
}
}
// Following two functions will convert mouse coordinates
// from screen to three.js system (where [0,0] is in the middle of the screen)
function updateMouseCoords(event, coordsObj) {
coordsObj.x = ((event.clientX - renderer.domElement.offsetLeft + 0.5) / window.innerWidth) * 2 - 1;
coordsObj.y = -((event.clientY - renderer.domElement.offsetTop + 0.5) / window.innerHeight) * 2 + 1;
}
function handleManipulationUpdate() {
raycaster.setFromCamera(mouse, camera);
{
var intersects = raycaster.intersectObjects(tooltipEnabledObjects);
if (intersects.length > 0) {
latestMouseProjection = intersects[0].point;
hoveredObj = intersects[0].object;
}
}
if (tooltipDisplayTimeout || !latestMouseProjection) {
clearTimeout(tooltipDisplayTimeout);
tooltipDisplayTimeout = undefined;
hideTooltip();
}
if (!tooltipDisplayTimeout && latestMouseProjection) {
tooltipDisplayTimeout = setTimeout(function() {
tooltipDisplayTimeout = undefined;
showTooltip();
}, 330);
}
}
function onMouseMove(event) {
updateMouseCoords(event, mouse);
latestMouseProjection = undefined;
hoveredObj = undefined;
handleManipulationUpdate();
}
window.addEventListener('mousemove', onMouseMove, false);
animate();
HTML code:
<p style="margin-left: 12px;">Mouse hover verts to see vert index and coordinates</p>
<div id="tooltip"></div>
CSS of tooltip element:
#tooltip {
position: fixed;
left: 0;
top: 0;
min-width: 10px;
text-align: center;
padding: 2px 2px;
font-family: monospace;
background: #a0c020;
display: none;
opacity: 0;
border: 0px solid transparent;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.5);
transition: opacity 0.25s linear;
border-radius: 0px;
}
Given approach allows to attach and display any text info per vertex.
My problem is the following : The mousehover actions works on the cubes even if the mouse is not directly over the cubes, it works if it is on an Y axis over or under the cubes, out of the scene. Can someone explain me why and how to fix it?
<!DOCTYPE html>
<html lang="fr" xml:lang="fr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="lib/Three.js" type="text/javascript"></script>
<script src="lib/Detector.js"></script>
<script src="lib/stats.min.js" type="text/javascript"></script>
<script src="lib/THREEx/THREEx.WindowResize.js"></script>
<script src="lib/THREEx/THREEx.FUllScreen.js"></script>
<script src="lib/TrackballControls.js"></script>
<style type="text/css">
body
{
color: #ffffff;
text-align:center;
background-color: gray;
margin: 0px;
}
#center
{
color: #fff;
position: absolute;
top: 50px; width: 100%;
padding: 5px;
z-index:100;
}
#center h1
{
font-size:60px;
}
#container
{
position:absolute;
bottom:0;
}
</style>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div id="container"></div>
</body>
<script>
// MAIN
console.log("Main.js");
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
// global variables
var container, scene, camera, renderer, stats, controls;
// custom variables
var t = THREE;
var cube;
// to keep track of the mouse position
var projector, INTERSECTED, mouse = { x: 0, y: 0 },
// an array to store our particles in
particles = [];
init();
animate();
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,0,800);
camera.lookAt(scene.position);
// renderer
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
// container
container = document.getElementById('container');
container.appendChild( renderer.domElement );
// stats
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
// events
THREEx.WindowResize(renderer, camera);
THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
// initialize object to perform world/screen calculations
projector = new THREE.Projector();
// CUSTOM
// Cubes
x = window.innerWidth / 5;
y = window.innerHeight / 10;
console.log(window.innerWidth);
console.log(window.innerHeight);
var geometry = new t.CubeGeometry(125,125,125);
var material = new t.MeshBasicMaterial({color:0xCCCCCC});
cube = new t.Mesh(geometry, material);
cube.name = "cube";
scene.add(cube);
cube.position.set(-x,-y,0);
x = window.innerWidth;
y = window.innerHeight / 10;
var geometry2 = new t.CubeGeometry(125,125,125);
var material2 = new t.MeshBasicMaterial({color:0xCCCCCC});
cube2 = new t.Mesh(geometry2, material2);
scene.add(cube2);
cube2.name = "cube2";
cube2.position.set(0,-y,0);
x = window.innerWidth / 5;
y = window.innerHeight / 10;
var geometry3 = new t.CubeGeometry(125,125,125);
var material3 = new t.MeshBasicMaterial({color:0xCCCCCC});
cube3 = new t.Mesh(geometry3, material3);
cube3.name = "cube3";
scene.add(cube3);
cube3.position.set(x,-y,0);
// particles
makeParticles();
// Mouse events
document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'mousedown', onMouseDown, false );
}
// called when the mouse moves
function onMouseMove( event )
{
// store the mouseX and mouseY position
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
function onMouseDown( event )
{
event.preventDefault();
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( scene.children );
if ( intersects.length > 0 )
{
console.log(INTERSECTED.name);
if(INTERSECTED.name == "cube")
{
page("real");
}
}
}
function animate()
{
cube.rotation.y +=0.005;
cube.rotation.x -=0.005;
cube2.rotation.y +=0.005;
cube2.rotation.x -=0.005;
cube3.rotation.y +=0.005;
cube3.rotation.x -=0.005;
//textMesh.rotation.y +=0.005;
requestAnimationFrame( animate );
render();
update();
}
// creates a random field of Particle objects
function makeParticles()
{
var particle, material;
// we're gonna move from z position -1000 (far away)
// to 1000 (where the camera is) and add a random particle at every pos.
for ( var zpos= -1000; zpos < 1000; zpos+=20 )
{
// we make a particle material and pass through the
// colour and custom particle render function we defined.
material = new THREE.ParticleCanvasMaterial( { program: particleRender } );
// make the particle
particle = new THREE.Particle(material);
// give it a random x and y position between -500 and 500
particle.position.x = Math.random() * 1000 - 500;
particle.position.y = Math.random() * 1000 - 500;
// set its z position
particle.position.z = zpos;
// scale it up a bit
particle.scale.x = particle.scale.y = 10;
// add it to the scene
scene.add( particle );
// and to the array of particles.
particles.push(particle);
}
}
// there isn't a built in circle particle renderer
// so we have to define our own.
function particleRender( context )
{
// we get passed a reference to the canvas context
context.beginPath();
// and we just have to draw our shape at 0,0 - in this
// case an arc from 0 to 2Pi radians or 360ยบ - a full circle!
context.arc( 0, 0, 0.2, 2, Math.PI * 4, true );
context.fillStyle = "white";
context.fill();
};
// moves all the particles dependent on mouse position
function updateParticles()
{
// iterate through every particle
for(var i=0; i<particles.length; i++)
{
particle = particles[i];
// and move it forward dependent on the mouseY position.
particle.position.z += 250 * 0.02;
// if the particle is too close move it to the back
if(particle.position.z>1000) particle.position.z-=2000;
}
}
function render()
{
renderer.render( scene, camera );
}
function update()
{
updateParticles();
stats.update();
// find intersections
// create a Ray with origin at the mouse position
// and direction into the scene (camera direction)
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
// create an array containing all objects in the scene with which the ray intersects
var intersects = ray.intersectObjects( scene.children );
// INTERSECTED = the object in the scene currently closest to the camera
// and intersected by the Ray projected from the mouse position
// if there is one (or more) intersections
if ( intersects.length > 0 )
{
// if the closest object intersected is not the currently stored intersection object
if ( intersects[ 0 ].object != INTERSECTED)
{
// restore previous intersection object (if it exists) to its original scale
if ( INTERSECTED )
{
INTERSECTED.scale.x = INTERSECTED.currentscale.x;
INTERSECTED.scale.y = INTERSECTED.currentscale.y;
INTERSECTED.scale.z = INTERSECTED.currentscale.z;
}
// store reference to closest object as current intersection object
INTERSECTED = intersects[ 0 ].object;
// store scale of closest object (for later restoration)
scalex = INTERSECTED.scale.x;
scaley = INTERSECTED.scale.y;
scalez = INTERSECTED.scale.z;
INTERSECTED.currentscale = { x : scalex , y : scaley, z : scalez };
// set a new scale for closest object
INTERSECTED.scale.x = INTERSECTED.scale.y = INTERSECTED.scale.z = 1.5;
}
}
else // there are no intersections
{
// restore previous intersection object (if it exists) to its original scale
if ( INTERSECTED )
{
INTERSECTED.scale.x = INTERSECTED.currentscale.x;
INTERSECTED.scale.y = INTERSECTED.currentscale.y;
INTERSECTED.scale.z = INTERSECTED.currentscale.z;
}
// remove previous intersection object reference
// by setting current intersection object to "nothing"
INTERSECTED = null;
}
}
// Pour charger une page dynamiquement
function page(page){
$("body").animate({opacity:0},1000, function(){
$("body").empty();
$("body").load(page +'.html');
$("body").animate({opacity:1},1000, function(){
});
});
}
</script>
</html>
Is there an offset between the window top left corner and the canvas top left corner?
If so, you have to calculate the offset (top and left) and subtract the values from the event.client values.
Try this :
// now get the space between top left browser window corner
var absoluteOffsetLeft = 0;
var absoluteOffsetTop = 0;
var obj = <your HTML object containing the canvas>;
// taken from http://www.quirksmode.org/js/findpos.html
if (obj.offsetParent) {
do {
absoluteOffsetLeft += obj.offsetLeft;
absoluteOffsetTop += obj.offsetTop;
} while (obj = obj.offsetParent);
} else {
console.log("Method offsetParent not supported");
}
// YOUR mouse move event handler - also take the innerWidth and Height from the canvas
function onMouseMove( event ) {
// store the mouseX and mouseY position
mouse.x = ( (event.clientX - absoluteOffsetLeft) / canvas.innerWidth ) * 2 - 1;
mouse.y = - ( (event.clientY - absoluteOffsetTop) / canvas.innerHeight ) * 2 + 1;
}
I'm trying to set up a website that runs in a single WebGL element. I'm trying to get it to tell when the mouse is over an object. I'm using a couple of planes with a with transparent textures on them as links, but it won't pick up on any intersections at all. It does absolutely nothing. I've even added a cube and used the same code as the interactive cubes example (http://mrdoob.github.com/three.js/examples/webgl_interactive_cubes.html) and it does absolutely nothing. No changing the color, absolutely nothing.
I've gone through and tried about 8 different examples online having to do with this and not a single one has worked for me.
Here is my code:
<meta charset="utf-8">
<style type="text/css">
body {
margin: 0px;
overflow: hidden;
background: #000000;
}
div {
margin: 0px;
}
</style>
</head>
<div>
<script src="http://www.html5canvastutorials.com/libraries/Three.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//Variable Declarations
var camera, scene, renderer, aspect, projector;
var INTERSECTED;
var mouseX = 0, mouseY = 0;
init();
//Method Declarations
function init() {
aspect = window.innerWidth / window.innerHeight;
//aspect = 1.25;
//Sets the camera variable to a new Perspective Camera with a field of view of 45 degrees, an aspect ratio
//of the window width divided by the window height, the near culling distance of 1 and the far culling distance of 2000
camera = new THREE.PerspectiveCamera(45, aspect, 1, 2000);
//Sets the height of the camera to 400
camera.position.z = 700;
//Sets a variable "lookat" to a new 3d vector with a position of 0, 0, 0,
//or the center of the scene/center of the menu plane
var lookat = new THREE.Vector3(0, 0, 0);
//Uses a function built in to every camera object to make it look at a given coordinate
camera.lookAt(lookat);
//Makes a new scene object to add everything to
scene = new THREE.Scene();
//Adds the camera object to the scene
scene.add(camera);
//Sets the renderer varialbe to a new WebGL renderer object
//Change "WebGLRenderer" to "CanvasRenderer" to use canvas renderer instead
renderer = new THREE.WebGLRenderer({antialias:true});
//renderer.sortObjects = false;
//Sets the size of the renderer object to the size of the browser's window
//renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setSize(window.innerWidth, window.innerHeight);
//Adds an event listener to the webpage that "listens" for mouse movements and when the mouse does move, it runs the
//"onMouseMove" function
document.addEventListener('mousemove', onMouseMove, false);
//Force canvas to stay proportional to window size
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousedown', onDocumentMouseDown, false);
//Sets the update frequency of the webpage in milliseconds
setInterval(update, 1000/60);
//Makes a variable "texture" and sets it to the returned value of the method "loadTexture"
//supplied by the THREE.js library
var texture = THREE.ImageUtils.loadTexture('imgs/backgrounds.png');
//Makes a variable "geometry" and sets it to a "PlaneGeometry" object with a width of 645 and a height of 300
var geometry = new THREE.PlaneGeometry(645, 300);
//Makes a variable "material" and sets it to a "MeshBasicMaterial" object with it's map set to
//the "texture" object, it also makes it transparent
var material = new THREE.MeshBasicMaterial({map: texture, transparent: true});
//Makes a variable "plane" and sets it to a "Mesh" object with its geometry set to the "geometry" object
//and it's material set to the "material" object
var plane = new THREE.Mesh(geometry, material);
//Background Texture
var backgroundTexture = THREE.ImageUtils.loadTexture('imgs/gears.png');
var backgroundGeo = new THREE.PlaneGeometry(3500, 2500);
var backgroundMat = new THREE.MeshBasicMaterial({map: backgroundTexture});
var backgroundPlane = new THREE.Mesh(backgroundGeo, backgroundMat);
backgroundPlane.position.z = -1000;
backgroundPlane.overdraw = true;
//Home Button
//Makes a "homeTexture" variable and sets it to the returned value of the makeTextTexture function when
//the text passed in is set to "Home", the width is set to 300, height of 150, font set to 80pt Arial,
//fillStyle set to white, textAlign set to center, textBaseLine set to middle, and the color of the
//background set to red = 0, green = 0, blue = 0 and alpha = 0
var homeTexture = makeTextTexture("Home", 300, 150, '80pt Arial', 'white', "center", "middle", "rgba(0,0,0,0)");
var homeGeom = new THREE.PlaneGeometry(50, 25);
var homeMaterial = new THREE.MeshBasicMaterial({map: homeTexture, transparent: true});
var homeTest = new THREE.Mesh(homeGeom, homeMaterial);
homeTest.position.x -= 270;
homeTest.position.y += 120;
homeTest.position.z = 40;
homeTest.castShadow = true;
//Gallery Button
var galleryTexture = makeTextTexture("Gallery", 340, 150, '80pt Arial', 'white', "center", "middle", "rgba(0,0,0,0)");
var galleryGeom = new THREE.PlaneGeometry(50, 25);
var galleryMaterial = new THREE.MeshBasicMaterial({map: galleryTexture, transparent: true});
var galleryTest = new THREE.Mesh(galleryGeom, galleryMaterial);
galleryTest.position.x -= 270;
galleryTest.position.y += 90;
galleryTest.position.z = 40;
galleryTest.castShadow = true;
//The Team Button
var theTeamTexture = makeTextTexture("Company", 510, 150, '80pt Arial', 'white', "center", "middle", "rgba(0,0,0,0)");
var theTeamGeom = new THREE.PlaneGeometry(80, 25);
var theTeamMaterial = new THREE.MeshBasicMaterial({map: theTeamTexture, transparent: true});
var theTeamTest = new THREE.Mesh(theTeamGeom, theTeamMaterial);
theTeamTest.position.x -= 260;
theTeamTest.position.y += 60;
theTeamTest.position.z = 40;
theTeamTest.castShadow = true;
projector = new THREE.Projector();
var cubeGeom = new THREE.CubeGeometry(20, 20, 20);
var cubeMat = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
var cubeMesh = new THREE.Mesh(cubeGeom, cubeMat);
cubeMesh.position.z = 15;
//scene.add(cubeMesh);
//Adds all of the previously created objects to the scene
scene.add(plane);
scene.add(backgroundPlane);
scene.add(homeTest);
scene.add(theTeamTest);
scene.add(galleryTest);
//Adds the renderer to the webpage
document.body.appendChild(renderer.domElement);
}
function update() {
camera.position.x = (mouseX - (window.innerWidth / 2)) * 0.1;
camera.position.y = -((mouseY - (window.innerHeight / 2)) * 0.15);
camera.lookAt(new THREE.Vector3(0, 0, 0));
render();
}
function render() {
renderer.render(scene, camera);
}
function onMouseMove(event) {
mouseX = event.clientX;
mouseY = event.clientY;
}
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 ray = new THREE.Ray( camera.position,
vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( objects );
if ( intersects.length > 0 ) {
intersects[ 0 ].object.materials[ 0 ].color.setHex( Math.random() * 0xffffff );
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function makeTextTexture(text, width, height, font, fillStyle, textAlign, textBaseline, backgroundColor)
{
//Makes a new canvas element
var bitmap = document.createElement('canvas');
//Gets its 2d css element
var g = bitmap.getContext('2d');
//Sets it's width and height
bitmap.width = width;
bitmap.height = height;
//Takes "g", it's 2d css context and set's all of the following
g.font = font;
g.fillStyle = backgroundColor;
g.fillRect(0, 0, width, height);
g.textAlign = "center";
g.textBaseline = "middle";
g.fillStyle = fillStyle;
g.fillText(text, width / 2, height / 2);
//Rendered the contents of the canvas to a texture and then returns it
var texture = new THREE.Texture(bitmap);
texture.needsUpdate = true;
return texture;
}
</script>
</div>
</html>
Thanks to anyone that can help out. I wish I could figure out what's going on myself, it seems like I'm using StackOverflow to answer my questions way too much.
You have not declared the variable objects. Do this:
var objects = [];
Then populate it:
objects.push( plane );
objects.push( backgroundPlane );
Now, this line will work:
var intersects = ray.intersectObjects( objects );