Get different alert box on each iframe click - javascript

<!DOCTYPE html>
<html>
<head>
<title>three.js css3d - youtube</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 {
background-color: #ffffff;
margin: 0;
overflow: hidden;
}
#blocker {
/* background-color: rgba(255, 0, 0, 0.5); */
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/controls/TrackballControls.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/renderers/CSS3DRenderer.js"></script>
<div id="container"></div>
<div id="blocker"></div>
<script>
var camera, scene, renderer, glrenderer, glscene;
function createGlRenderer() {
var container = document.getElementById('container');
glrenderer = new THREE.WebGLRenderer({
antialias: false
});
glrenderer.setClearColor(0xffffff);
glrenderer.setPixelRatio(window.devicePixelRatio);
glrenderer.setSize(window.innerWidth, window.innerHeight);
glrenderer.domElement.style.position = 'absolute';
glrenderer.domElement.style.top = 0;
container.appendChild(glrenderer.domElement);
return glrenderer;
}
function createCssrenderer() {
var container = document.getElementById('container');
var renderer = new THREE.CSS3DRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute';
// renderer.domElement.style.zIndex = 1;
renderer.domElement.style.top = 0;
container.appendChild(renderer.domElement);
return renderer;
}
function createPlane(w, h, position, rotation) {
var material = new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.0,
side: THREE.DoubleSide
});
var geometry = new THREE.PlaneGeometry(w, h);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.x = position.x;
mesh.position.y = position.y;
mesh.position.z = position.z;
mesh.rotation.x = rotation.x;
mesh.rotation.y = rotation.y;
mesh.rotation.z = rotation.z;
return mesh;
}
var Element = function(id, w, h, position, rotation, myfunc) {
var html = [
'<div id="blocker" style="width:' + w + 'px; height:' + h + 'px;">',
'<iframe src="' + id + '" width="' + w + '" height="' + h + '" onclick="' + myfunc + '">',
'</iframe>',
'</div>'
].join('\n');
var div = document.createElement('div');
$(div).html(html);
div.style.width = w;
div.style.height = h;
//div.style.backgroundColor = '#000';
var object = new THREE.CSS3DObject(div);
object.position.x = position.x;
object.position.y = position.y;
object.position.z = position.z;
object.rotation.x = rotation.x;
object.rotation.y = rotation.y;
object.rotation.z = rotation.z;
return object;
var plane = createPlane(
w, h,
position,
rotation);
glscene.add(plane);
}
function myfunctiona() {
alert("I am an alert box!");
}
init();
animate();
function init() {
glscene = new THREE.Scene();
glrenderer = createGlRenderer();
scene = new THREE.Scene();
renderer = createCssrenderer();
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 100, 3000);
var ambientLight = new THREE.AmbientLight(0xffffff, 1);
glscene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(-.5, .5, -1.5).normalize();
glscene.add(directionalLight);
var group = new THREE.Group();
group.add(new Element('http://adndevblog.typepad.com/cloud_and_mobile', 1000, 1000, new THREE.Vector3(-1000, 0, 100), new THREE.Vector3(0, -50 * Math.PI / 180, 0), myfunctiona()));
group.add(new Element('http://adndevblog.typepad.com/cloud_and_mobile', 900, 1000, new THREE.Vector3(0, 0, 500), new THREE.Vector3(0, 0, 0)));
group.add(new Element('http://adndevblog.typepad.com/cloud_and_mobile', 1000, 1000, new THREE.Vector3(1000, 0, 100), new THREE.Vector3(0, 50 * Math.PI / 180, 0)));
scene.add(group);
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 4;
window.addEventListener('resize', onWindowResize, false);
// Block iframe events when dragging camera
var blocker = document.getElementById('blocker');
blocker.style.display = 'none';
document.addEventListener('mousedown', function() {
blocker.style.display = '';
});
document.addEventListener('mouseup', function() {
blocker.style.display = 'none';
});
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
glrenderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
glrenderer.render(glscene, camera);
}
$(document).ready(function() {
initialize();
});
</script>
</body>
</html>
I am firing a javascript function whenever an iframe is clicked. But that javascript alert is loading with page itself and not when iframe is clicked. Iframe is embedded on three.js scene. Can anybody tell me what is wrong with my code.

Related

ThreeJS and PhysiJS "Class constructor cannot be invoked without 'new'

I'm trying to implement PhysiJS to my ThreeJS project.
To simplify I have downloaded this project from the web:
https://rawgit.com/mmmovania/Physijs_Tutorials/master/MultipleBoxes.html
My project setup is available here:
https://drive.google.com/drive/folders/1lO-8YQtWkOPDhsEpk1LzuPajoPjsBnyo?usp=sharing
Problem
When I have downloaded all the files (html, js) I tried to run it.
When it's run from my computer I receive an error.
I'm still very new to JavaScript I kind of understand what the problem is but not sure how to solve it. What am I missing? It's the exact same project on my PC as it is on the web.
Here's the error:
**three.js:34977 THREE.Quaternion: .inverse() has been renamed to invert().
Quaternion.inverse # three.js:34977
physi.js:391 Uncaught TypeError: Class constructor Scene cannot be invoked without 'new'
at new window.Physijs.Physijs.Scene (physi.js:391)
at init (MultipleBoxes.html:71)
at MultipleBoxes.html:51**
Change init() to window.onload = init(); to give the script files a chance to load completely before you init().
'use strict';
var initScene, render, renderer, scene, camera, box, floor;
var container;
var camera, scene, controls, renderer;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var clock;
var NUM_BOXES = 10;
// always wait for all scripts to load before doing assignments
window.onload = function() {
init();
animate();
}
function init() {
// initialize your script and set assignments
Physijs.scripts.worker = 'js/physijs_worker.js';
Physijs.scripts.ammo = 'ammo.js';
clock = new THREE.Clock();
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.z = 20;
camera.position.y = 5;
controls = new THREE.OrbitControls(camera);
// scene
//scene = new THREE.Scene();
scene = new Physijs.Scene;
scene.setGravity(new THREE.Vector3(0, -10, 0));
//floor
floor = new Physijs.BoxMesh(
new THREE.CubeGeometry(20, 0.1, 20),
new THREE.MeshPhongMaterial({
color: 0xffffff
}),
0 //mass
);
floor.receiveShadow = true;
floor.position.set(0, 0, 0);
scene.add(floor);
var loader = new THREE.ImageLoader(manager);
var crateTexture = new THREE.Texture();
loader.load('textures/crate.jpg', function(image) {
crateTexture.image = image;
crateTexture.needsUpdate = true;
});
// Box
var boxGeometry = new THREE.CubeGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshPhongMaterial({
color: 0xffffff,
map: crateTexture
});
for (var i = 0; i < NUM_BOXES; ++i) {
var box = new Physijs.BoxMesh(boxGeometry, boxMaterial);
box.castShadow = true;
box.position.y = 10 + 2 * i;
scene.add(box);
}
var manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
var ambientLight = new THREE.AmbientLight(0x707070);
scene.add(ambientLight);
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(-10, 18, 5);
light.castShadow = true;
var d = 14;
light.shadow.camera.left = -d;
light.shadow.camera.right = d;
light.shadow.camera.top = d;
light.shadow.camera.bottom = -d;
light.shadow.camera.near = 2;
light.shadow.camera.far = 50;
light.shadow.mapSize.x = 1024;
light.shadow.mapSize.y = 1024;
scene.add(light);
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
container.appendChild(renderer.domElement);
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) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var deltaTime = clock.getDelta();
controls.update(deltaTime);
scene.simulate(); // run physics
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display: block;
}
#info a,
.button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Physijs + THREE.js = Multiple Boxes Demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
/* moved to separate box for stackoverflow answer
(see CSS box)
*/
</style>
</head>
<body>
<script src="js/three.js"></script>
<script type="text/javascript" src="js/physi.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script>
/* moved to javascript box */
</script>
</body>
</html>

Three.js: How to add envMap correctly?

Now I want to have a material like here:
https://threejs.org/examples/#webgl_materials_envmaps_exr
So I would add the following:
* {
margin: 0;
padding: 0;
}
.object {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
background-color: rgb(200, 200, 200);
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import { OBJLoader } from "https://threejs.org/examples/jsm/loaders/OBJLoader.js";
var container;
var camera, scene, renderer;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff, 2);
pointLight.position.set(100, 100, 50);
camera.add(pointLight);
scene.add(camera);
// manager
function loadModel() {
object.traverse(function (child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.1,
metalness: 0.4
});
child.material.flatShading = false;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
// model
function onProgress(xhr) {
if (xhr.lengthComputable) {
var percentComplete = (xhr.loaded / xhr.total) * 100;
console.log("model " + Math.round(percentComplete, 2) + "% downloaded");
}
}
function onError() {}
var loader = new OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function (obj) {
object = obj;
},
onProgress,
onError
);
//
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
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) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
Unfortunately, it does not work. Why?
I would be very thankful if somebody could help me! :)
The main issue is that newEnvMap is not ready when the object was loaded.
In general, the main steps to add an Environment Map to a scene are:
Import EXRLoader.
Create a "Prefiltered, Mipmapped Radiance Environment Map (PMREM)" with THREE.PMREMGenerator.
Load the EXR (or the JPG image) with new EXRLoader() (or with THREE.TextureLoader().load()).
Once EXR is loaded, objects must be updated with this setting. In the CodePen, this is done with the function loadObjectAndAndEnvMap(). This function loads the model and updates envMap with object.material.envMap = newEnvMap;.
Don't forget to object.material.needsUpdate = true.
Finally, if you want to visualize the background itself, it is needed to set scene.background = background; inside the render function.
(Extra) In case the environment map is still not visible, check for the roughness, metalness and envMapIntensity of your materials. It is a common mistake to set values that don't reflect the environment. Here are a few setting examples:
Demo:
* {
margin: 0;
padding: 0;
}
.object {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
background-color: rgb(200, 200, 200);
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import { OBJLoader } from "https://threejs.org/examples/jsm/loaders/OBJLoader.js";
import { EXRLoader } from "https://threejs.org/examples/jsm/loaders/EXRLoader.js";
var container;
var camera, scene, renderer;
let exrCubeRenderTarget, exrBackground;
let newEnvMap;
let torusMesh, planeMesh;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var object;
init();
animate();
function init() {
container = document.createElement("div");
container.className = "object";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
2000
);
camera.position.z = 250;
// scene
scene = new THREE.Scene();
/*var ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff, 2);
pointLight.position.set(100, 100, 50);
camera.add(pointLight);*/
scene.add(camera);
// manager
function loadModel() {
THREE.DefaultLoadingManager.onLoad = function () {
pmremGenerator.dispose();
};
// -----------------
function loadObjectAndAndEnvMap() {
object.traverse(function (child) {
//This allow us to check if the children is an instance of the Mesh constructor
if (child instanceof THREE.Mesh) {
child.material = new THREE.MeshStandardMaterial({
color: "#555",
roughness: 0.0,
metalness: 2.0,
envMapIntensity: 5.0
});
//child.material.flatShading = false;
console.log("setting envmap");
child.material.envMap = newEnvMap;
child.material.needsUpdate = true;
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
}
});
object.position.y = -90;
scene.add(object);
}
const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
new EXRLoader()
.setDataType(THREE.UnsignedByteType)
.load(
"https://threejs.org/examples/textures/piz_compressed.exr",
function (texture) {
exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
exrBackground = exrCubeRenderTarget.texture;
newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;
loadObjectAndAndEnvMap(); // Add envmap once the texture has been loaded
texture.dispose();
}
);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
}
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
// model
function onProgress(xhr) {
if (xhr.lengthComputable) {
var percentComplete = (xhr.loaded / xhr.total) * 100;
console.log("model " + Math.round(percentComplete, 2) + "% downloaded");
}
}
function onError() {}
var loader = new OBJLoader(manager);
loader.load(
"https://threejs.org/examples/models/obj/female02/female02.obj",
function (obj) {
object = obj;
},
onProgress,
onError
);
//
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
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) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
scene.background = exrBackground;
renderer.toneMappingExposure = 1.0;
renderer.render(scene, camera);
}
</script>
In case you don't like SO snippets, here is the CodePen version you can vote/fork/share.
You can now use scene.environment as the environment map for all physical materials in the scene. However, it's not possible to overwrite an existing texture assigned to MeshStandardMaterial.envMap. Doc

when I switch camera,camera control is bing valid

I want to swith camera type in my threejs Demo,so I read an official demo :https://threejs.org/examples/#webgl_camera
But some errors occur when I test my demo. When I press P to use cameraPerspective,it works well;But when I use O to switch cameraOrtho,cameracontrol doesn't work——I cannot rotate or move my model sample.
There is my code:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>3D-earth</title>
<script src="JSandCSS/jquery-2.2.4.min.js"></script>
<script src="JSandCSS/three.min.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script type="text/javascript" src="JSandCSS/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="JSandCSS/qrcode.js"></script>
<script src="JSandCSS/bootstrap.min.js"></script>
<script type="text/javascript" src="JSandCSS/CanvasRenderer.js"></script>
<script src="JSandCSS/Projector.js"></script>
<link href="JSandCSS/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div style="width: 50%;">
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
init();
var container, stats, titleinfo;
scene.add(group);
var textureLoader = new THREE.TextureLoader();
var mat = new THREE.MeshLambertMaterial({
/* Roushness:1,
Metalness:0,*/
map: textureLoader.load("model/earth/texture.jpg"),
/* normalMap:textureLoader.load("model/earth/normal.jpg"),*/
specularMap: textureLoader.load("model/earth/specular.jpg"),
lightMap: textureLoader.load("model/earth/light.jpg"),
side:THREE.DoubleSide,
});
var loader = new THREE.OBJLoader();
loader.load('model/earth/earth.obj', function(obj) {
obj.traverse(function(child) {
if(child instanceof THREE.Mesh) {
child.material = mat;
}
});
mesh = obj;
obj.scale.set(2, 2, 2);
group.add(obj);
});
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var cameraPerspective = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
cameraPerspective.position.set(200, 200, 200);
cameraPerspective.lookAt(scene.position);
cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -4, window.innerWidth / 4, window.innerHeight / 4, window.innerHeight / -4, -10000, 10000);
ActiveCamera = cameraPerspective;
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, ActiveCamera);
renderer.setClearColor(0x808080, 0.5);
var controls = new THREE.OrbitControls(ActiveCamera);
controls.minDistance = 200;
controls.maxDistance = 400;
controls.autoRotate = true;
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
document.addEventListener('keydown', onKeyDown, false);
function render() {
/*group.rotation.y -= 0.004;*/
renderer.render(scene, ActiveCamera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function onKeyDown(event) {
switch(event.keyCode) {
case 79:
ActiveCamera = cameraOrtho;
case 80:
ActiveCamera = cameraPerspective;
}
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
ActiveCamera.aspect = WIDTH / HEIGHT;
ActiveCamera.updateProjectionMatrix();
}
</script>
</div>
</body>
try with single camera object of CombinedCamera and
to switch between Perspective and Ortho use below code.
//initial
var camera = new THREE.CombinedCamera($(canvasHold).innerWidth(), $(canvasHold).innerHeight(), 75, .1, 3e3, -5e3, 5e3);
camera.toOrthographic();
function switchCamera()
{
if(ortho) // Add condition
{
camera.toOrthographic();
camera.position.set(0, 0, 0);
camera.zoom = .5;
camera.up = new THREE.Vector3(0, 0, 0);
camera.lookAt(scene.position);
camera.setFov(75);
}
else
{
camera.toPerspective();
camera.zoom = 1;
camera.setFov(45);
}
}
Note: Please change variables and values according to your requirements.

three.js adding object to scene but not rendering object

I'm creating a function createCylinder(n, len, rad) that is called from function createScene(). I have checked that the vertices and faces are added and I get no errors. However, the geometry is not rendered. I suppose this has to do with the timing of returning the geometry or returning the mesh and adding it to the scene. That being said, I have tried everything I could think of and found no solution. Can someone please help me figure this out? Thanks in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cylinder</title>
</head>
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="OrbitControls.js"></script>
<style>
body {
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
<body>
<div id="container">
</div>
<div id="msg">
</div>
<script type="text/javascript">
var camera, scene, renderer;
var cameraControls;
var clock = new THREE.Clock();
var isCappedBottom = false;
var isCappedTop = false;
function createCylinder(n, len, rad) {
var geometry = new THREE.Geometry();
var radius = rad;
var length = len;
var yUp = length / 2;
var yDown = -length / 2;
var theta = (2.0 * Math.PI) / n;
for (var i = 0; i < n ; i++) { //runs n + 2 times if we allow redundant vertices
var x = radius * Math.cos(i * theta);
var z = radius * Math.sin(i * theta);
//Top to bottom
var originUp = new THREE.Vector3(x, yUp, z);
var originDown = new THREE.Vector3(x, yDown, z);
geometry.vertices.push(originUp); //0
geometry.vertices.push(originDown); //1
console.log("Vertices " + geometry.vertices.length);
}//end of first for loop
// Draw faces
for (var j = 0; j < 2*n; j+= 2) {
var face1 = new THREE.Face3(j, j + 1, j + 2);
var face2 = new THREE.Face3(j + 1, j + 3, j + 2);
geometry.faces.push(face1);
geometry.faces.push(face2);
console.log("faces " + geometry.faces.length);
}
// return geometry;
//scene.add(geometry);
var material = new THREE.MeshLambertMaterial({color: 0xFF0000, side: THREE.DoubleSide});
var mesh = new THREE.Mesh(geometry, material);
return mesh;
scene.add(mesh);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x222222);
scene.add(ambientLight);
var light = new THREE.PointLight(0xFFFFFF, 1, 1000);
light.position.set(0, 10, 20);
scene.add(light);
var light2 = new THREE.PointLight(0xFFFFFF, 1, 1000);
light2.position.set(0, -10, -10);
scene.add(light2);
} //End of function
function createScene() {
var cyl = createCylinder(10, 10, 2);
return cyl;
scene.add(cyl);
}
function animate() {
window.requestAnimationFrame(animate);
render();
}
function render() {
var delta = clock.getDelta();
cameraControls.update(delta);
renderer.render(scene, camera);
}
function init() {
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
var canvasRatio = canvasWidth / canvasHeight;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({antialias: true, preserveDrawingBuffer: true});
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.setSize(canvasWidth, canvasHeight);
renderer.setClearColor(0x000000, 1.0);
renderer.shadowMapEnabled = true;
camera = new THREE.PerspectiveCamera( 40, canvasRatio, 1, 1000);
/* camera.position.z = 5;
camera.lookAt(scene.position); */
camera.position.set(0, 0, 12);
camera.lookAt(new THREE.Vector3(0, 0, 0));
cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
}
function addToDOM() {
var container = document.getElementById('container');
var canvas = container.getElementsByTagName('canvas');
if (canvas.length>0) {
container.removeChild(canvas[0]);
}
container.appendChild( renderer.domElement );
}
init();
createScene();
addToDOM();
render();
animate();
</script>
</body>
</html>
In the createCylinder function:
var mesh = new THREE.Mesh(geometry, material);
return mesh; // this line must be the last line in the function
// after return(), the rest of the code is unreacheable
//scene.add(mesh); // this line should be deleted as you add the mesh in the createScene() function
and then the createScene function should be like this:
function createScene() {
var cyl = createCylinder(10, 10, 2);
//return cyl;
scene.add(cyl);
}
jsfiddle example

Why raycaster.intersectObjects work fine with Geometry built in scene but work bad with model loaded form exterior?

I wanna make a measure tool in three.js,and I use reycaster function to do it.
When I use it with Geometry built in scene,it was fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var geometry = new THREE.SphereGeometry(5, 32, 32);
geometry.scale(10, 10, 10);
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var sphere = new THREE.Mesh(geometry, material);
group.add(sphere);
objects.push(sphere);
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, 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);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
enter image description here
But When I loaded a model,it doesn't work.As you see result of "alert(intersects.length)" is 0.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var textureLoader = new THREE.TextureLoader();
var mat = new THREE.MeshLambertMaterial({
map: textureLoader.load("model/earth/texture.jpg"),
specularMap: textureLoader.load("model/earth/specular.jpg"),
lightMap: textureLoader.load("model/earth/light.jpg")
});
var loader = new THREE.OBJLoader();
loader.load('model/earth/earth.obj',
function chuanzhi(obj) {
obj.traverse(function(child) {
if(child instanceof THREE.Mesh) {
child.material = mat;
}
});
Mesh = obj;
obj.scale.set(2, 2, 2);
group.add(obj);
objects.push(Mesh);
});
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, 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);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
alert(intersects.length);
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
I wanna know why it happened,and how I can use it correctly.Could you help me ?

Categories

Resources