I have a particle which is an image. When I rotate the particle it leaves a circle behind. How do I get rid of this strange circle?
The Fiddle is here: http://jsfiddle.net/zUvsp/137/
Code:
var camera, scene, renderer, material, img, texture, particle;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1000;
scene.add(camera);
img = new Image();
texture = new THREE.Texture(img);
img.onload = function() {
texture.needsUpdate = true;
makeParticle();
};
img.src = "http://www.atalasoft.com/cs/blogs/davidcilley/files/PNG_Mask.png";
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function makeParticle() {
material = new THREE.ParticleBasicMaterial({
map: texture,
blending: THREE.AdditiveBlending,
});
// make the particle
particle = new THREE.Particle(material);
particle.scale.x = particle.scale.y = 1;
particle.position.x = 10;
scene.add(particle);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
particle.rotation.z += 0.01
}
-EDIT
I tested my theory, its not the issue, don't waste your time
Just a guess, but I think it might have something to do with you loading the texture .png from a different domain.
Try using an image loaded from the same domain your code is running on, and see if that fixes the problem.
I think the issue might have something to do with three.js not being able to access the pixel data on the texture, because of the Cross-origin issue.
Related
I'm setting up a 3d asset viewer in Three.js. I'm running the code on a Plesk server provided by the university and have it linked via Dreamweaver. I'm a total newbie to JS and it was suggested in many threads and posts that I wrap my code within an 'init();' function. Up doing so, and clearing any errors that the code had, it is now showing a black screen, rather than the 3d model it would show before.
I've spent the whole day error checking removing problems that I was having which included the 'canvas' not being created inside the 'container' div, and the 'onWindowResize' function. All these problems have been resolved, and there are no errors in the code apparently. I've got ambient lights in the code and there was a working skybox, so I'm sure its not a problem with position of camera or lack of lighting.
I know that you need as little code as possible, but I have no idea where the problem is coming from, so a majority of the code on the page is here :
<div id="container" ></div>
<script>
let container;
let camera;
let controls;
let scene;
let renderer;
init();
animate;
function init(){
// Renderer - WebGL is primary Renderer for Three.JS
var renderer = new THREE.WebGLRenderer({antialias : true});
renderer.setClearColor(0xEEEEEE, 0.5);
// Selects and applies parameters to the 'Container' div
var container = document.querySelector("#container");
container.appendChild(renderer.domElement);
renderer.setSize(container.clientWidth, container.clientHeight);
// Perspective Camera (FOV, aspect ratio based on container, near, far)
var camera = new THREE.PerspectiveCamera( 75, container.clientWidth / container.clientHeight, 0.1, 1000);
camera.position.x = 750;
camera.position.y = 500;
camera.position.z = 1250;
// Scene will contain all objects in the world
var scene = new THREE.Scene();
//Lighting (Colour, intensity)
var light1Ambient = new THREE.AmbientLight(0xffffff , 0.3);
scene.add(light1Ambient);
var light1Point = new THREE.PointLight(0xfff2c1, 0.5, 0, 2);
scene.add(light1Point);
var light2Point = new THREE.PointLight(0xd6e3ff, 0.4, 0, 2);
scene.add(light2Point);
// All basic Geomety
var newPlane = new THREE.PlaneGeometry(250,250,100,100);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial( {color: 0x00ff00} )
);
scene.add(mesh);
// Water
water = new THREE.Water(newPlane,
{
textureWidth: 512,
textureHeight: 512,
waterNormals: new THREE.TextureLoader().load( 'http://up826703.ct.port.ac.uk/CTPRO/textures/waternormals.jpg', function ( texture ) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
} ),
alpha: 1.0,
sunDirection: light1Point.position.clone().normalize(),
sunColor: 0xffffff,
waterColor: 0x001e0f,
distortionScale: 0.5,
fog: scene.fog !== undefined
}
);
water.rotation.x = - Math.PI / 2;
scene.add( water );
// All Materials (Normal for Debugging) (Lambert: color)
var material = new THREE.MeshLambertMaterial({color: 0xF3FFE2});
var materialNew = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
// Skybox
var skybox = new THREE.BoxGeometry(1000,1000, 1000);
var skyboxMaterials =
[
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_ft.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_bk.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_up.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_dn.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_rt.jpg"), side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("http://up826703.ct.port.ac.uk/CTPRO/skybox/blue/bluecloud_lf.jpg"), side: THREE.DoubleSide }),
];
var skyboxMaterial = new THREE.MeshFaceMaterial(skyboxMaterials);
var skyMesh = new THREE.Mesh (skybox, skyboxMaterial);
scene.add(skyMesh);
//Grid Helper Beneath Ship
scene.add(new THREE.GridHelper(250, 250));
//OBJ Model Loading
var objLoader = new THREE.OBJLoader();
objLoader.load('http://up826703.ct.port.ac.uk/CTPRO/models/ship1.obj', function(object){
scene.add(object);
});
// Object positioning
water.position.y = -2.5;
// Misc Positioning
light1Point.position.z =20;
light1Point.position.x = 25;
// z - front-back position
light2Point.position.z = -400;
// x - left-right
light2Point.position.x = -25;
// y - up- down
light2Point.position.y = 250;
window.addEventListener("resize", onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
};
};
// Canvas adapts size based on changing windows size
//Render loop
var animate = function(){
water.material.uniforms[ "time" ].value += 1.0 / 120.0;
function drawFrame(ts){
var center = new THREE.Vector2(0,0);
window.requestAnimationFrame(drawFrame);
var vLength = newPlane.geometry.vertices.length;
for (var i = 0; i < vLength; i++) {
var v = newPlane.geometry.vertices[i];
var dist = new THREE.Vector2(v.x, v.y).sub(center);
var size = 2.0;
var magnitude = 8;
v.z = Math.sin(dist.length()/-size + (ts/900)) * magnitude;
}
newPlane.geometry.verticesNeedUpdate = true;
};
requestAnimationFrame(animate)
renderer.render(scene, camera);
controls.update();
}
</script>
I'm no professional, so I'm sorry if this is super rough for those of you with experience!
I need to point out, before wrapping all of this in the init(); function, it was working perfectly.
When working, I should see a crudely modeled ship sitting in some water, with a cloud skybox. The controls were working and it would auto rotate.
Right now it does none of this. The obj loader is working as seen in the chrome console log OBJLoader: 1661.970703125ms but again, nothing is actually displayed, it's just a black screen.
Thanks to anyone who's able to help me out with this!
this line
animate;
needs to a function call
animate();
Also you probably need to change the code below where you create the animate function from
var animate = function(){
To this
function animate(){
The reason is named functions are defined when the code is loaded but variables var are created when the code is executed. So with code like this
init();
animate();
var animate = function(){ ...
animate doesn't actually exist at the point the code tries to call it whereas with this
init();
animate();
function animate(){ ...
it does exist
You could also re-arrange the code so for example define animate before you use it should work.
var animate = function(){
...
};
init();
animate();
It also appear some are declared inside init which means that are not available to animate. So for example
var renderer = new THREE.WebGLRenderer({antialias : true});
declares a new variable renderer that only init can see. You wanted to set the renderer variable that is outside of init so change the code to
renderer = new THREE.WebGLRenderer({antialias : true});
controls is never defined so you probably need to define it or comment out
controls.update();
to
// controls.update();
note: you might find these tutorials helpful although if you're new to JavaScript you should probably spend time learning JavaScript
So I'm working on a ThreeJS WebVR Page. (I'm quite new to three.js)
So I tired to make a basic scene to test some stuff. But when I load the page with renderer.setAnimationLoop(render) I get my green cube for 1 Frame and then it disappears.
(I got it working with requestAnimationFrame() but this will not work with WebVR)
This is my code for my test sandbox:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 10);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.vr.enabled = true;
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function render() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
function animate() {
renderer.setAnimationLoop(render);
}
animate();
//Button vor start VR Session
document.body.appendChild(WEBVR.createButton(renderer));
Not the problem with setAnimationLoop
The problem is you cannot set camera position when vr is enabled
check this stack overflow question
Unable to change camera position when using VRControls
Check this CodePen Link where i fixed your code by changing position of cube instead of camera
var cube = new THREE.Mesh(geometry, material);
cube.position.z = -5; //added this instead of camera.position.z = 5;
if you want to move the camera you need make it as child of another object and set the position to that object
I'm pretty beginner in three.js and webgl programming. so I have created a box in three.js and its working fine but the problem is when I set camera position in z axis(eg: camera.position.z = 2; ) the box just disappears. could anyone explain me why is it happening and how can I properly set the position of the camera?
try uncommenting the camera.position.z = 2; in the fiddle
function init() {
var scene = new THREE.Scene();
var box = getBox(1, 1, 1);
scene.add(box);
var camera = new THREE.Camera(45, window.innerWidth/window.innerHeight, 1, 1000 );
//camera.position.z = 2;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("webgl").appendChild(renderer.domElement);
renderer.render(scene, camera);
}
function getBox(w, h, d) {
var geometry = new THREE.BoxGeometry(w, h, d);
var material = new THREE.MeshBasicMaterial({
color : 0x00ff00
});
var mesh = new THREE.Mesh(geometry, material);
return mesh;
}
init();
not sure if you're trying to create this scene with an orthographic camera or perspective camera, but you'll typically need to specify the camera by type (ie THREE.PerspectiveCamera(...)).
I also added a few extra lines to ensure the camera was configured correctly, namely, setting the "LookAt" point to (0,0,0) , as well as setting an actual position of the camera via the THREE.Vector3.set(...) method.
Here are my adjustments to your code:
function init() {
var scene = new THREE.Scene();
var box = getBox(1, 1, 1);
scene.add(box);
var camera = new THREE.PerspectiveCamera(70,
window.innerWidth/window.innerHeight, 0.1, 1000 ); // Specify camera type like this
camera.position.set(0,2.5,2.5); // Set position like this
camera.lookAt(new THREE.Vector3(0,0,0)); // Set look at coordinate like this
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("webgl").appendChild(renderer.domElement);
renderer.render(scene, camera);
}
function getBox(w, h, d) {
var geometry = new THREE.BoxGeometry(w, h, d);
var material = new THREE.MeshBasicMaterial({
color : 0x00ff00
});
var mesh = new THREE.Mesh(geometry, material);
return mesh;
}
init();
Try
camera.position.set( <X> , <Y> , <Z> );
where <X> and <Z> are 2D coordinates and <Y> is height
I'm an old COBOL programmer, teaching myself a bit of Javascript and Three.js for a little personal project, and I've got struck now with this doubt for almost two days.
I've read all the questions about OrbitControls here in StackOverflow, and couldn't find anything related to what I'm trying to do. So any help would be appreciated.
I have a scene that's like the image below:
And here's what my Script Looks like right Now:
var container, renderer, scene, camera, controls;
var Main = {
Init: function () {
document.getElementById("comprimento").innerHTML = "Comprimento: " + localStorage.storLength / 100;
document.getElementById("largura").innerHTML = "Largura: " + localStorage.storWidth / 100;
document.getElementById("altura").innerHTML = "Altura: " + localStorage.storHeight / 100;
document.getElementById("quadrado").innerHTML = "Metros²: " + localStorage.storSquare;
Main.Render();
Main.Camera();
Main.Draw();
Main.Update();
// events
window.addEventListener('resize', onWindowResize, false);
},
Render: function () {
renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffe6ff);
container = document.getElementById("building");
document.body.appendChild(container);
container.appendChild(renderer.domElement);
// Inicializacao da Cena
scene = new THREE.Scene();
},
Camera: function () {
//Inicializacao da Camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
//Posicao da Camera nos eixos X,Y,Z
camera.position.set(0, 100, 800);
camera.lookAt(scene.position);
//Controle de Camera
controls = new THREE.OrbitControls(camera, renderer.domElement);
//Controle de Iluminação
var light = new THREE.PointLight(0xffffff);
light.position.set(100, 250, 250);
scene.add(light);
},
Draw: function () {
var planeGeometry = new THREE.PlaneGeometry(localStorage.storWidth, localStorage.storLength, 10, 10);
var planeMaterial = new THREE.MeshLambertMaterial({
color: 0x888888,
side: THREE.DoubleSide
});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
},
Update: function () {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(Main.Update);
}
}
function onWindowResize(event) {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.render(scene, camera);
}
Main.Init();
This works just fine for using the orbitControl, while the mouse is over the part where the rendered materials are.
What I'm trying to do is, limit the Orbit control functionality to only be usable while the mouse is over the little green div that is overlaying the render scene. I've tried messing up with the parameters of the OrbitControl, tried adding onMouseOver functions on the javascript, associated with the div in the html, but nothing seems to work.
What I'm trying to do is even possible? If so, what am I missing?
Thanks in advance.
If I got you correctly, let's suppose, that you have a little green div
<div style="position: absolute;" id="LittleGreenDiv"></div>
Then you can use it as the second parameter when you create the object of controls:
var controls = new THREE.OrbitControls(camera, document.getElementById("LittleGreenDiv"));
jsfiddle example.
I am trying to apply texture to my sphere mesh with the following.
var loader = new THREE.TextureLoader();
var balltex = loader.load("pic1.jpg");
var ballmat = new THREE.MeshBasicMaterial({ map:balltex });
var ballgeo = new THREE.SphereGeometry( 0.3, 20, 20 );
var ball = new THREE.Mesh( ballgeo , ballmat );
scene.add(ball);
Now I am just getting a black sphere instead of textured sphere. I do not know what is the problem in the code.
Please help me.
It's hard to say for sure without a complete example, but my first guess is the simplest case: the texture isn't finished loading by the time the mesh is rendered.
If that's the problem, make sure the texture(s) are loaded before you call your render loop. There are many ways to do this and it's hard to say which is best without seeing your code, but the most straightforward way to handle it is pass a function to the loader's load() method and call your renderer from it. A simple but complete example reworking the code you posted:
var scene, camera, light, renderer, balltex;
load();
function load() {
var loader;
loader = new THREE.TextureLoader(new THREE.LoadingManager());
loader.load('pic1.jpg', function(obj) {
balltex = obj;
init();
animate();
});
}
function init() {
var height = 500, width = 500, bg = '#000000';
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, height/width, 1, 10000);
camera.position.set(1.5, 1.5, 1.5);
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene.add(camera);
light = new THREE.AmbientLight(0xffffff);
scene.add(light);
var ballmat = new THREE.MeshBasicMaterial({
map: balltex
});
var ballgeo = new THREE.SphereGeometry( 0.3, 20, 20 );
var ball = new THREE.Mesh( ballgeo , ballmat );
scene.add(ball);
renderer = new THREE.WebGLRenderer({ antialias: true } );
renderer.setClearColor(bg);
renderer.setSize(width, height);
var d = document.createElement('div');
document.body.appendChild(d);
d.appendChild(renderer.domElement);
var c = document.getElementsByTagName('canvas')[0];
c.style.width = width + 'px';
c.style.height = height + 'px'
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}