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

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>

Related

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

Displacement map in three.js

I'm currently using a black and white image as a bump map for my model. The model is an .obj file with the associated .mtl file for UV mapping. This is the code I use:
// Load material file
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath('/models/');
mtlLoader.load('model.mtl', function (materials) {
materials.preload();
// Load obj file
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('/models/');
objLoader.load('model.obj', function (group) {
var geometry = group.children[0].geometry;
model = new THREE.Mesh(geometry, otherModel.material.clone());
scene.add(model);
render();
callback();
});
});
At a latter time I add the bump map when I need it:
model.material.bumpMap = new THREE.Texture(canvas);
model.material.bumpScale = 0.8;
model.material.bumpMap.format = THREE.RGBFormat;
model.material.bumpMap.wrapS = mapRingModel.material.bumpMap.wrapT = THREE.RepeatWrapping;
model.material.bumpMap.minFilter = THREE.LinearFilter;
model.material.bumpMap.needsUpdate = true;
model.material.needsUpdate = true;
This works as expected but now I would like to use my texture as a displacement map instead of a bump map so I changed my code to:
model.material.displacementMap = new THREE.Texture(canvas);
model.material.displacementScale = 0.8;
model.material.displacementMap.format = THREE.RGBFormat;
model.material.displacementMap.wrapS = model.material.displacementMap.wrapT = THREE.RepeatWrapping;
model.material.displacementMap.minFilter = THREE.LinearFilter;
model.material.displacementMap.needsUpdate = true;
model.material.needsUpdate = true;
With the same texture applied the displacement is no applied at all. Is there anything I need to change on my UV mapping or texture to work as the bump map but with displacement?
I don't see anything wrong with your code. Are you sure it's not working?
Try upping the value of displacementScale.
While bumpScale is from 0 - 1. DisplacementScale can be anything as it is .. umm...scene scale.
below is an example of both working together with canvas as texture (draw in boxes to see), click "run code snippet"
var camera, scene, renderer, mesh, material, stats;
var drawStartPos = {x:0, y:0};
init();
setupCanvasDrawing();
animate();
function init() {
// Renderer.
renderer = new THREE.WebGLRenderer();
//renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// Add renderer to page
document.getElementById('threejs-container').appendChild(renderer.domElement);
// Create camera.
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 400;
// Create scene.
scene = new THREE.Scene();
// Create material
material = new THREE.MeshPhongMaterial();
// Create cube and add to scene.
var geometry = new THREE.BoxGeometry(200, 200, 200, 50, 50, 50);
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// Create ambient light and add to scene.
var light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);
// Create directional light and add to scene.
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Add listener for window resize.
window.addEventListener('resize', onWindowResize, false);
// Add stats to page.
stats = new Stats();
document.body.appendChild( stats.dom );
}
function setupCanvasDrawing() {
// get canvas and context
var drawingCanvas = document.getElementById('drawing-canvas');
var drawingCanvas2 = document.getElementById('drawing-canvas-2');
var drawingContext = drawingCanvas.getContext('2d');
var drawingContext2 = drawingCanvas2.getContext('2d');
// draw white background
drawingContext.fillStyle = "#FFFFFF";
drawingContext.fillRect(0,0,128,128);
drawingContext2.fillStyle = "#000000";
drawingContext2.fillRect(0,0,128,128);
// set canvas as bumpmap
material.bumpMap = new THREE.Texture(drawingCanvas);
material.displacementMap = new THREE.Texture(drawingCanvas2);
material.displacementScale = 30;
// set the variable to keep track of when to draw
var paint = false;
var paint2 = false;
// add canvas event listeners
drawingCanvas.addEventListener('mousedown', function(e){
paint = true
drawStartPos = {x:e.offsetX, y:e.offsetY};
});
drawingCanvas.addEventListener('mousemove', function(e){
if(paint){
draw(drawingContext, 0, e.offsetX, e.offsetY);
}
});
drawingCanvas.addEventListener('mouseup', function(e){
paint = false;
});
drawingCanvas.addEventListener('mouseleave', function(e){
paint = false;
});
drawingCanvas2.addEventListener('mousedown', function(e){
paint2 = true
drawStartPos = {x:e.offsetX, y:e.offsetY};
});
drawingCanvas2.addEventListener('mousemove', function(e){
if(paint2){
draw(drawingContext2, 1, e.offsetX, e.offsetY);
}
});
drawingCanvas2.addEventListener('mouseup', function(e){
paint2 = false;
});
drawingCanvas2.addEventListener('mouseleave', function(e){
paint2 = false;
});
}
// Draw function
function draw(drawContext, type, x, y) {
drawContext.moveTo(drawStartPos.x, drawStartPos.y);
if(type){
// is displacement
drawContext.strokeStyle = '#ffffff';
}else{
// is bump
drawContext.strokeStyle = '#000000';
}
drawContext.lineTo(x,y);
drawContext.stroke();
drawStartPos = {x:x, y:y};
material.bumpMap.needsUpdate = true;
material.displacementMap.needsUpdate = true;
}
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x += 0.005;
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
stats.update();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
padding: 0;
margin: 0;
}
#drawing-canvas {
position: absolute;
background-color: #000;
top: 0px;
right: 0px;
z-index: 3;
}
#drawing-canvas-2 {
position: absolute;
background-color: #000;
top: 128px;
right: 0px;
z-index: 3;
border: solid 1px #ffffff;
}
#threejs-container {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 1;
}
<script src="https://rawgit.com/mrdoob/three.js/r83/build/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/stats.js/r17/build/stats.min.js"></script>
<canvas id="drawing-canvas" height="128" width="128"></canvas>
<canvas id="drawing-canvas-2" height="128" width="128"></canvas>
<div id="threejs-container"></div>

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.

Get different alert box on each iframe click

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

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