Trying to load a STL model into a canavas with Threejs is giving me an error every time the animate function is runned;
Uncaught TypeError: Cannot read property 'render' of undefined
at animate (
I know the STL file is good it worked before.
Here is my code;
// Globals
var scene, camera, light, renderer;
init();
animate();
// Sets up the scene.
function init() {
// Create the scene and set the scene size.
scene = new THREE.Scene();
//Scene Lighting
scene.add( new THREE.AmbientLight( 0x000000 ) );
//Renderer
var renderer = new THREE.WebGLRenderer({canvas: document.getElementById('modelCan'), antialias:true});
renderer.setClearColor(0xfffffff);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize( window.innerWidth/3, window.innerHeight/3 );
//Camera
var camera = new THREE.PerspectiveCamera(1000, window.innerWidth/window.innerHeight, 1, 10000);
scene.add(camera);
//Camera Lightning
var light = new THREE.PointLight( 0xffffff, 1);
camera.add( light );
var loader = new THREE.STLLoader();
loader.load( 'Sac_Fuel_Tank.stl', function ( geometry ) {
var material = new THREE.MeshLambertMaterial( { color: 0x286617,
wireframe: true
} );
var mesh = new THREE.Mesh( geometry, material );
mesh.rotation.x = Math.PI / 2;
mesh.position.set(20,10,-10);
// mesh.rotation.z = Math.PI;
scene.add( mesh );
} );
controls = new THREE.OrbitControls(camera, renderer.domElement);
}
function animate() {
// Read more about requestAnimationFrame at http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame(animate);
// Render the scene.
renderer.render(scene, camera);
controls.update();
}
So what am I doinng wrong?
You have to remove the var keyword when creating the renderer. Just do:
renderer = new THREE.WebGLRenderer( { canvas: document.getElementById('modelCan'), antialias:true } );
Related
I'm trying to learn something new in three.js. My goal is to be able to use what a second camera sees in a separate scene as a texture for the main scene.
Or alternatively to be able to use what a second camera sees in the main scene as a texture. But i only see a black screen. I posted my code for it here. I hope someone recognizes where my mistake is, because I just can't figure it out.
In 3 steps:
texture = second camera view
material use texture
apply material ordinary to a mesh
see below
var camera, controls, scene, renderer, container, aspect;
function main() {
init();
animate();
}
function init() {
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container = document.getElementById('container');
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild( renderer.domElement );
aspect = container.clientWidth / container.clientHeight;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x000000 );
camera = new THREE.PerspectiveCamera( 60, container.clientWidth / container.clientHeight, 1, 1000000 );
camera.position.set(0, 0, 200);
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableZoom = true;
controls.enabled = true;
controls.target.set(0, 0, 0);
//-----End three basic setups-----
var tex = generateTexture(renderer);
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry(100.0, 100.0),
new THREE.MeshBasicMaterial({
color: 0x00caff,
map: tex,
side: THREE.DoubleSide,
})
);
scene.add(plane);
}//-------End init----------
function animate() {
requestAnimationFrame( animate );
render();
}//-------End animate----------
function render() {
camera.updateMatrixWorld();
camera.updateProjectionMatrix();
renderer.render(scene, camera);
}//-------End render----------
function generateTexture(renderer) {
var resolution = 2000;
var textureScene = new THREE.Scene();
textureScene.background = new THREE.Color(0x404040);
var renderTarget = new THREE.WebGLRenderTarget(resolution, resolution, {minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat});
var textureCamera = new THREE.PerspectiveCamera(60, aspect, 0.1, 100000.0);
textureCamera.position.set(0, 0, 200);
textureCamera.lookAt(0, 0, 0);
var geometry = new THREE.SphereGeometry( 60, 32, 16 );
var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
var sphere = new THREE.Mesh( geometry, material);
textureScene.add( sphere );
//---changes---
renderer.setRenderTarget( renderTarget );
renderer.clear();
renderer.render( textureScene, textureCamera );
renderer.setRenderTarget(null);
return renderTarget.texture;
//-------------
//---now it works fine---:)
}//----- End generateTexture ------
Are you copying this approach from a tutorial? What version of three.js are you using? I'm asking because you're using renderer.render(scene, camera, target, true); but the docs state that .render() only accepts two arguments, so passing a renderTarget doesn't do anything.
I recommend you copy the approach in this demo, you can see the source code by clicking on the < > icon. The essential part is as follows:
// Render first scene into texture
renderer.setRenderTarget( renderTarget );
renderer.clear();
renderer.render( textureScene, textureCamera );
// Render full scene to canvas
renderer.setRenderTarget( null );
renderer.clear();
renderer.render( scene, camera );
I'm loading a .glb model into three.js, and while I have it rotating automatically using OrbitControls, I'm not able to see how to change the pivot point so the rotating model is centered.
I've seen a lot of questions on setting boxes or pivot points with rotation, but not with OrbitControls and autorotate. Is there a way for me to center the imported model using autorotate as per my code below?
var scene = new THREE.Scene();
// Load Camera Perspective
var camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 1, 8000 );
camera.position.set( 200, 100, 0 );
// Load a Renderer
var renderer = new THREE.WebGLRenderer({ alpha: false });
renderer.setClearColor( 0xC5C5C3 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Load the Orbitcontroller
var controls = new THREE.OrbitControls( camera, renderer.domElement );
camera.position.set( 60, 20, 100 );
controls.update();
controls.autoRotate = true;
controls.minDistance = 700;
controls.maxDistance = 2000;
//controls.update();
// Load Light
var ambientLight = new THREE.AmbientLight( 0xcccccc );
scene.add( ambientLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 0, 1, 1 ).normalize();
scene.add( directionalLight );
// glTf 2.0 Loader
var loader = new THREE.GLTFLoader();
loader.load( 'BTR.glb', function ( gltf ) {
var object = gltf.scene;
gltf.scene.scale.set( 1, 1, 1 );
gltf.scene.position.x = 0; //Position (x = right+ left-)
gltf.scene.position.y = 0; //Position (y = up+, down-)
gltf.scene.position.z = 0; //Position (z = front +, back-)
scene.add( gltf.scene );
});
function animate() {
// required if controls.enableDamping or controls.autoRotate are set to true
controls.update();
render();
requestAnimationFrame( animate );
}
function render() {
renderer.render( scene, camera );
}
render();
animate();
I think this issue can be solved by setting Controls.target (the focus point) to the center point of your glTF asset. You should be able to do this like so:
var aabb = new THREE.Box3().setFromObject( gltf.scene );
aabb.getCenter( controls.target );
controls.update();
three.js R107
Correct way to set target.
var aabb = new THREE.Box3().setFromObject( gltf.scene );
controls.target.set(aabb.getCenter());
controls.update();
it should take (aab.getCenter()), as it returns a vector3 with 3 axis values. But I found this didn't work for me, so I used the following
let aabb = new THREE.Box3().setFromObject( gltf.scene );
let aabbc = aabb.getCenter()
controls.target.set(aabbc.x, aabbc.y, aabbc.z);
controls.update();
just separating into 3 values, if you ever get stuck just console.log(whateveryourstuckwith) and read through the methods and variables and stuff, really helped me understand Three.js more
I caeate outline according to this example https://threejs.org/examples/?q=out#webgl_postprocessing_outline.And this is the result.It is works well.But when i set scene.background=texture,it is not work.IAnd i check the three.js document about scene.background. (If not null, sets the background used when rendering the scene, and is always rendered first. Can be set to a Color which sets the clear color, a Texture covering the canvas, or a CubeTexture. Default is null).I want to find out why outline disappear.Here is the code.
var scene, camera, renderer;
var light, floor;
var WIDTH,HEIGHT;
var controls;
var composer;
var composer, effectFXAA, outlinePass;
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
init();
animation()
function init () {
scene = new THREE.Scene();
var textureLoader = new THREE.TextureLoader();
textureLoader.load('img/bg.png', function(texture){
scene.background = texture;
});
camera = new THREE.PerspectiveCamera(45, WIDTH/HEIGHT, 0.1, 800);
camera.position.set(0,150,150);
scene.add(camera);
scene.add(new THREE.AmbientLight(0xffffff));
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(WIDTH, HEIGHT);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
controls = new OrbitControls(camera);
var shape = new THREE.Shape();
shape.moveTo(0,4);
shape.lineTo(0,96);
shape.lineTo(4,100);
shape.lineTo(96,100);
shape.lineTo(100,96);
shape.lineTo(100,4);
shape.lineTo(96, 0 );
shape.lineTo(84,0);
shape.lineTo(80,4);
shape.lineTo(20, 4);
shape.lineTo(16, 0);
shape.lineTo(4, 0 );
shape.lineTo(0, 4);
var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings );
var material = new THREE.MeshLambertMaterial( { color: 0x0E2350 } );
mesh = new THREE.Mesh( geometry, material ) ;
mesh.rotation.x = -Math.PI/2;
mesh.translateX(-50);
mesh.translateY(-50);
scene.add(mesh);
composer = new THREE.EffectComposer( renderer );
var renderPass = new THREE.RenderPass( scene, camera );
composer.addPass( renderPass );
outlinePass = new THREE.OutlinePass( new THREE.Vector2( window.innerWidth, window.innerHeight ), scene, camera );
outlinePass.edgeStrength = 3;
outlinePass.edgeGlow = 3.0;
outlinePass.edgeThickness = 0.1;
outlinePass.visibleEdgeColor.setHex(0x19C0EE);
composer.addPass( outlinePass );
effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
effectFXAA.uniforms[ 'resolution' ].value.set( 1 / window.innerWidth, 1 / window.innerHeight );
effectFXAA.renderToScreen = true;
composer.addPass( effectFXAA );
outlinePass.selectedObjects = [mesh];
}
function animation() {
requestAnimationFrame(animation);
composer.render();
render();
controls.update();
};
function render () {
renderer.render(scene, camera)
};
my question is simple but for the life of me i cannot figure out what is going on. I am trying to set up a basic three.js scene and add a simple cube with a BaiscMaterial however the cube is not showing up in my scene.
"use strict";
var renderer, scene, camera;
var light;
function init() {
var canvasWidth = 850;
var canvasHeight = 450;
var canvasRatio = canvasWidth / canvasHeight;
camera = new THREE.PerspectiveCamera(45, canvasRatio, 0.9, 1000);
camera.position.set(0, 200, -550);
camera.lookAt(0, 0, 0);
light = new THREE.AmbientLight(0xFFFFFF, 1);
light.position.set(-800, 900, 300);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(canvasWidth, canvasHeight);
renderer.setClearColorHex(0x000000, 1.0); //canvas color
renderer.gammaInput = true;
renderer.gammaOutput = true;
}
function cube() {
var cubeGeo = new THREE.CubeGeometry(1000, 1000, 1000);
var cubeMaterial = new THREE.MeshBasicMaterial();
var cube1 = new THREE.Mesh(cubeGeo, cubeMaterial);
cube1.position.set(0, 0, 0);
return cube1;
}
function fillScene() {
scene = new THREE.Scene();
scene.add(light);
var cube = cube();
scene.add(cube);
}
function addToDOM() {
var container = document.getElementById('container');
var canvas = container.getElementsByTagName('canvas');
if (canvas.length > 0) {
container.removeChild(canvas[0]);
}
container.appendChild(renderer.domElement);
}
function render() {
fillScene();
renderer.render(scene, camera);
}
try {
init();
fillScene();
addToDOM();
render();
} catch (e) {
var errorReport = "Your Program encountered an ERROR, cannot draw on canvas. Error was:<br/><br/>";
$('#container').append(errorReport + e);
}
First of all, Cube is updated to BoxGeometry now. And I see lots of problem on your code and improper function definition and usage.
Here's a very simple example from mr.doob's Github.
var scene, camera, renderer;
var geometry, material, mesh;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
geometry = new THREE.BoxGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
See the demo here
P.S Three.js Docs is the best place for resources, it makes work alot easier with tons of example code.
Am trying to create an app which will import the 3D model exported from Blender/Maya into ThreeJS. I have installed Blender and three js export option is also coming, however when am trying to load the exported JS (I tried renaming extension to json also) it is not working and showing blank screen. Can anyone help me with this by providing a sample code for this?
TIA.
Regards,
NileshW
add a div to the body
<div id="myScene"></div>
then..
<script>
// global
var scene, renderer, camera, cube, controls;
init();
animate();
function init() {
// scene box
var myScene = document.getElementById("myScene");
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, .01, 10000);
camera.position.z = 500;
var light = new THREE.AmbientLight(0xffffff); // soft white light
scene.add(light);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
/* ==== OPTIONAL SPOTLIGHT ====
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(100, 1000, 2000);
spotLight.castShadow = true;
spotLight.shadowMapWidth = 1024;
spotLight.shadowMapHeight = 1024;
spotLight.shadowCameraNear = 500;
spotLight.shadowCameraFar = 4000;
spotLight.shadowCameraFov = 30;
scene.add(spotLight);
*/
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
myScene.appendChild(renderer.domElement);
loader = new THREE.JSONLoader();
loader.load("your_json_file.js", function (geometry, materials) {
mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial(materials));
scene.add(mesh);
});
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
Have you tried the code from chawk - just change to use your test.js (check folder path)
If the code in you function init() is complete then it looks like you've missed a couple of things
You have created a camera, created a scene, created a loader, loaded a file and added mesh to the scene
You need to add the camera to the scene
You also need to add some light(s) to your scene
var camera, scene, renderer;
var geometry, material, mesh;
var controls;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 5, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 50, 50, 50 );
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = false;
controls.dynamicDampingFactor = 0.3;
controls.keys = [ 65, 83, 68 ];
scene = new THREE.Scene();
var light = new THREE.PointLight(0xffffff);
light.position.set(-100,200,100);
scene.add(light);
// Load in the mesh and add it to the scene.
var loader = new THREE.JSONLoader();
loader.load( "models/testnew.js", function(geometry){
var material = new THREE.MeshNormalMaterial({color: 0x55B663});
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
});
//
renderer = new THREE.CanvasRenderer();
renderer.setSize( 1000, 600);
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}