I have a simple demo that works fine in Chrome and Firefox. But Safari is lag like hell. If I disable antialising, it increases the FPS but not that much. How can i optimize my code ? Maybe use some caching? I'm new to three.js
It will be nice if it will work in iOs safari too.
Here's the demo:
var $container = $('#torus');
var mouseX = 0,
mouseY = 0;
var camera, scene, renderer;
var geometry, material, mesh, config;
var numTorus = 65;
var tabTorus = [];
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
config = {
speed: 1.3,
rotation: 1,
opacity: 1
}
function init() {
camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 10, 1000);
camera.position.z = 1;
scene = new THREE.Scene();
material = new THREE.MeshNormalMaterial();
material.transparent = true;
material.opacity = config.opacity;
geometry = new THREE.TorusGeometry(130, .5, 120, 100);
geometry.computeFaceNormals();
geometry.computeVertexNormals();
geometry.normalsNeedUpdate = true;
geometry.verticesNeedUpdate = true;
geometry.dynamic = true;
for (var i = 0; i < numTorus; i++) {
tabTorus.push(new Torus(-i * 6));
scene.add(tabTorus[i].b);
}
renderer = new THREE.WebGLRenderer({
antialias: true,
autoClear: true,
alpha: true,
});
renderer.setSize(window.innerWidth, window.innerHeight);
$container.append(renderer.domElement);
}
function Torus(f) {
this.b = new THREE.Mesh(geometry, material);
this.b.position.y = 55 * Math.sin(f);
this.b.position.x = 55 * Math.cos(f);
this.b.position.z = f * 2.72;
}
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) / 10;
mouseY = (event.clientY - windowHalfY) / 10;
}
function update() {
for (var i = 0; i < numTorus; i++) {
tabTorus[i].b.position.z += config.speed * 1.5;
tabTorus[i].b.material.opacity = config.opacity;
tabTorus[i].b.geometry.parameters.arc = 0.5 + config.opacity * 10;
if (tabTorus[i].b.position.z > 0) {
tabTorus[i].b.position.z = -1000;
}
}
}
function animate() {
requestAnimationFrame(animate);
camera.position.x += (mouseX - camera.position.x) * .02;
camera.position.y += (-mouseY - camera.position.y) * .02;
renderer.render(scene, camera);
update();
}
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
init();
animate();
body {
background: black;
}
#torus {
position: fixed;
width: 100%;
height: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div id="torus"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
It seems to be a problem in Safari itself: enormous amounts of time spent compositing the page (40-50ms on my machine vs 2-4 ms for JavaScript). Also, it depends on size of the window. You should report it to https://bugs.webkit.org.
Related
I looked at this example with three js to draw particles with images and works perfectly but i want to change the image with a switch when click a button (calls this function):
const changeImg = function(num) {
switch (num)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA....";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoAAAAN..."
break;
}
img.src = imgData;
}
And works but when you click multiple times website becomes slow.
How can I update just the image without slowing down the website?
EDIT 1
I change the code like this:
var renderer, scene, camera, ww, wh, particles, mw, mh, mz, numState;
numState = 0;
mz = 6; // Matrerial size
ww = document.getElementById('map-container').offsetWidth,
wh = 450;
mw = ww * 2;
mh = wh * 2;
var centerVector = new THREE.Vector3(0, 0, 0);
var previousTime = 0
speed = 10
isMouseDown = false;
// Render
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("map"),
antialias: true
});
renderer.setSize(mw, mh);
renderer.setClearColor(0x12347C);
// Scence
scene = new THREE.Scene();
// Camera
camera = new THREE.OrthographicCamera( ww / - 2, ww / 2, wh / 2, wh / - 2, 1, 1000 );
camera.position.set(7, 0, 4);
camera.lookAt(centerVector);
scene.add(camera);
camera.zoom = 4;
camera.updateProjectionMatrix();
// Geometry
var geometry = new THREE.Geometry();
var material = new THREE.PointsMaterial({
size: mz,
color: 0xFFFFFF,
sizeAttenuation: false
});
// Particle
particles = new THREE.Points();
var getImageData = function(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
var drawTheMap = function() {
geometry.dispose();
particles.material.dispose();
particles.geometry.dispose();
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
geometry.vertices.push(vertex);
}
}
}
particles.material = material;
particles.geometry = geometry;
scene.add(particles);
requestAnimationFrame(render);
};
var init = function() {
imagedata = getImageData(image);
drawTheMap();
onResize();
window.addEventListener('mousemove', onMousemove, false);
window.addEventListener('mousedown', onMousedown, false);
window.addEventListener('mouseup', onMouseup, false);
window.addEventListener('resize', onResize, false);
};
var onResize = function(){
var mov1, mov2;
ww = document.getElementById('map-container').offsetWidth;
wh = 450;
if (window.innerWidth > 850) {
mw = ww * 2;
mh = wh * 2;
mz = 6;
mov1 = 2.2;
mov2 = 1.9;
particles.material.size = mz;
} else {
mw = ww;
mh = wh;
mz = 3;
mov1 = 2;
mov2 = 2;
particles.material.size = mz;
}
renderer.setSize(mw, mh);
camera.left = ww / - mov1;
camera.right = ww / 2;
camera.top = wh / mov2;
camera.bottom = wh / - 2;
camera.updateProjectionMatrix();
};
var onMouseup = function(){
isMouseDown = false;
}
var onMousedown = function(e){
isMouseDown = true;
lastMousePos = {x:e.clientX, y:e.clientY};
};
var onMousemove = function(e){
if(isMouseDown){
camera.position.x += (e.clientX-lastMousePos.x)/100;
camera.position.y -= (e.clientY-lastMousePos.y)/100;
camera.lookAt(centerVector);
lastMousePos = {x:e.clientX, y:e.clientY};
}
};
var render = function(a) {
requestAnimationFrame(render);
particles.geometry.verticesNeedUpdate = true;
if(!isMouseDown){
camera.position.x += (0-camera.position.x)*0.06;
camera.position.y += (0-camera.position.y)*0.06;
camera.lookAt(centerVector);
}
renderer.render(scene, camera);
};
var imgData;
var image;
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
const changeState = function(state, num) {
document.getElementById('dropbox-choose').innerHTML = state;
numState = num;
switch (numState)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoI..."
break;
}
image.src = imgData;
}
image = document.createElement("img");
image.onload = init;
image.src = imgData;
And the THREE.WebGLRenderer is only applied once but when I click to change the image, it does not update and also I still have the problem that the website slows down
it's my first time using three js and i don't know if i'm applying well what it says in the documentation
EDIT 2
var renderer, scene, camera, ww, wh, particles, mw, mh, mz, numState;
numState = 0;
mz = 6;
ww = document.getElementById('map-container').offsetWidth,
wh = 450;
mw = ww * 2;
mh = wh * 2;
var centerVector = new THREE.Vector3(0, 0, 0);
var previousTime = 0
speed = 10
isMouseDown = false;
// Render
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("map"),
antialias: true
});
renderer.setSize(mw, mh);
renderer.setClearColor(0x12347C);
// Scence
scene = new THREE.Scene();
// Camera
camera = new THREE.OrthographicCamera( ww / - 2, ww / 2, wh / 2, wh / - 2, 1, 1000 );
camera.position.set(7, 0, 4);
camera.lookAt(centerVector);
scene.add(camera);
camera.zoom = 4;
camera.updateProjectionMatrix();
// Geometry
//var geometry = new THREE.Geometry();
var material = new THREE.PointsMaterial({
size: mz,
color: 0xFFFFFF,
sizeAttenuation: false
});
// Particle
particles = new THREE.Points();
particles.material = material
scene.add(particles);
var getImageData = function(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
var drawTheMap = function() {
let vertices = particles.geometry; // this acts as a REFERENCE!
vertices.length = 0; // clears the vertices array
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
vertices.vertices.push(vertex);
}
}
}
particles.geometry.verticesNeedUpdate = true; // Inform three.js of the update
requestAnimationFrame(render);
};
var init = function() {
imagedata = getImageData(image);
drawTheMap();
onResize();
window.addEventListener('mousemove', onMousemove, false);
window.addEventListener('mousedown', onMousedown, false);
window.addEventListener('mouseup', onMouseup, false);
window.addEventListener('resize', onResize, false);
};
var onResize = function(){
var mov1, mov2;
ww = document.getElementById('map-container').offsetWidth;
wh = 450;
if (window.innerWidth > 850) {
mw = ww * 2;
mh = wh * 2;
mz = 6;
mov1 = 2.2;
mov2 = 1.9;
particles.material.size = mz;
} else {
mw = ww;
mh = wh;
mz = 3;
mov1 = 2;
mov2 = 2;
particles.material.size = mz;
}
renderer.setSize(mw, mh);
camera.left = ww / - mov1;
camera.right = ww / 2;
camera.top = wh / mov2;
camera.bottom = wh / - 2;
camera.updateProjectionMatrix();
};
var onMouseup = function(){
isMouseDown = false;
}
var onMousedown = function(e){
isMouseDown = true;
lastMousePos = {x:e.clientX, y:e.clientY};
};
var onMousemove = function(e){
if(isMouseDown){
camera.position.x += (e.clientX-lastMousePos.x)/100;
camera.position.y -= (e.clientY-lastMousePos.y)/100;
camera.lookAt(centerVector);
lastMousePos = {x:e.clientX, y:e.clientY};
}
};
var render = function(a) {
requestAnimationFrame(render);
particles.geometry.verticesNeedUpdate = true;
if(!isMouseDown){
camera.position.x += (0-camera.position.x)*0.06;
camera.position.y += (0-camera.position.y)*0.06;
camera.lookAt(centerVector);
}
renderer.render(scene, camera);
};
var imgData;
var image;
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
const changeState = function(state, num) {
document.getElementById('dropbox-choose').innerHTML = state;
numState = num;
switch (numState)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoAAA..."
break;
}
image.src = imgData;
}
image = document.createElement("img");
image.onload = init;
image.src = imgData;
When I click to change the image, it does not update and also I still have the problem that the website slows down. I cahaged vertcies.push to vertices.vertices.push()
I know I mentioned disposal in a previous version of my answer, but let's instead consider re-using all of your objects.
particles - Add it to the scene immediately after creation.
material - Assign it to particles immediately; No need to re-assign it every time.
geometry - Don't create it globally, we'll let it work from within particles.
Now what we're going to do is replace the vertices and tell three.js that there are new vertices to upload to the GPU.
var drawTheMap = function() {
let vertices = particles.geometry; // this acts as a REFERENCE!
vertices.length = 0; // clears the vertices array
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
vertices.push(vertex);
}
}
}
particles.geometry.verticesNeedUpdate = true; // Inform three.js of the update
requestAnimationFrame(render);
};
The important part here (other than replacing the contents of the vertices array) is setting particles.geometry.verticesNeedUpdate = true;. This is what triggers three.js to replace the vertices on the GPU. Everything else is re-used, not recreated, so it should run fairly smooth.
The solution is change THREE.geometry to THREE.BufferGeometry
var drawTheMap = function() {
particles.geometry = new THREE.BufferGeometry();
var positions = [];
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
positions.push(x - imagedata.width / 2);
positions.push(-y + imagedata.height / 2);
positions.push(-Math.random()*500);
particles.geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
}
}
}
particles.geometry.verticesNeedUpdate = true;
requestAnimationFrame(render);
};
I need to simulate the wave effect to the content on top of the wave background using three.js
In my case, the wave effect is working as my expectation but I need the contents will be up and down with the background effect. Like boats in sea waves
Mostly, you can achieve that by adding the wave effects to the background of the scene.
This link may help you
https://codepen.io/mweslander/pen/JreWPa
const SEPARATION = 100, AMOUNTX = 50, AMOUNTY = 50;
let container, stats;
let camera, scene, renderer;
let particles, particle, count = 0;
let mouseX = 0, mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
function init() {
container = document.createElement( 'div' );
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000; // Good var to change
scene = new THREE.Scene();
particles = new Array();
var PI2 = Math.PI * 2;
var geometry = new THREE.Geometry();
var material = new THREE.SpriteCanvasMaterial({
color: 0xffffff,
program: function ( context ) {
context.beginPath();
context.arc( 0, 0, 0.4, 0, PI2, true );
context.fill();
}
});
var i = 0;
for ( var ix = 0; ix < AMOUNTX; ix ++ ) {
for ( var iy = 0; iy < AMOUNTY; iy ++ ) {
particle = particles[ i ++ ] = new THREE.Sprite( material );
particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 );
particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 );
scene.add(particle);
if (i > 0) {
geometry.vertices.push( particle.position );
}
}
}
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
stats = new Stats();
container.appendChild( stats.dom );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, 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;
mouseY = event.clientY - windowHalfY;
}
function onDocumentTouchStart(event) {
if (event.touches.length === 1) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
mouseY = event.touches[ 0 ].pageY - windowHalfY;
}
}
function onDocumentTouchMove( event ) {
if (event.touches.length === 1) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
mouseY = event.touches[ 0 ].pageY - windowHalfY;
}
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
renderer.setClearColor( 0x07074e, 1);
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
var i = 0;
for (var ix = 0; ix < AMOUNTX; ix++) {
for (var iy = 0; iy < AMOUNTY; iy++) {
particle = particles[i++];
particle.position.y = (Math.sin((ix + count) * 0.3) * 50) + (Math.sin((iy + count) * 0.5) * 50);
particle.scale.x = particle.scale.y = (Math.sin((ix + count) * 0.3) + 1) * 4 + (Math.sin((iy + count) * 0.5) + 1) * 4;
}
}
renderer.render(scene, camera);
count += 0.1;
}
init();
animate();
This code causes a particle explosion on my page.
I attached the onClick function to a button in my HTML so it runs when I click that certain button. But when I load the HTML it automatically runs this function and after that only when I click the button.
What I need is that it wont rune when you run the HTML. The function may only run when the button is clicked.
I also would like to ask how I can change te canvas size. Since this function automatically creates a canvas where the function loads in but this one is bigger than the div with the sizes I want it to run in.
//////////////settings/////////
var movementSpeed = 30;
var totalObjects = 500;
var objectSize = 70;
var sizeRandomness = 0;
var color = 0x00BEE0;
/////////////////////////////////
var dirs = [];
var parts = [];
//var container = document.createElement('div');
//document.body.appendChild( container );
var container = document.getElementById('header');
//document.body.appendChild( header );
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000)
camera.position.z = 1000;
var scene = new THREE.Scene();
function ExplodeAnimation(x, y) {
var geometry = new THREE.Geometry();
for (i = 0; i < totalObjects; i++) {
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = y;
vertex.z = 0;
geometry.vertices.push(vertex);
dirs.push({
x: (Math.random() * movementSpeed) - (movementSpeed / 2),
y: (Math.random() * movementSpeed) - (movementSpeed / 2),
z: (Math.random() * movementSpeed) - (movementSpeed / 2)
});
}
var material = new THREE.ParticleBasicMaterial({
size: objectSize,
color: color
});
var particles = new THREE.ParticleSystem(geometry, material);
this.object = particles;
this.status = true;
this.xDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.yDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.zDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
scene.add(this.object);
this.update = function() {
if (this.status == true) {
var pCount = totalObjects;
while (pCount--) {
var particle = this.object.geometry.vertices[pCount]
particle.y += dirs[pCount].y;
particle.x += dirs[pCount].x;
particle.z += dirs[pCount].z;
}
this.object.geometry.verticesNeedUpdate = true;
}
}
}
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
function render() {
requestAnimationFrame(render);
var pCount = parts.length;
while (pCount--) {
parts[pCount].update();
}
renderer.render(scene, camera);
}
window.addEventListener('mousedown', onclick, false);
window.addEventListener('resize', onWindowResize, false);
function onClick() {
event.preventDefault();
parts.push(new ExplodeAnimation((Math.random() * sizeRandomness) - (sizeRandomness / 2), (Math.random() * sizeRandomness) - (sizeRandomness / 2)));
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
As I saw you code , I think you should only put your bellow trigger code inside the click button :
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
because it's executed automatically when loading .
See My below Snippet , I ve added a sample button and run() function to show animation on click :
//////////////settings/////////
var movementSpeed = 30;
var totalObjects = 500;
var objectSize = 70;
var sizeRandomness = 0;
var color = 0x00BEE0;
/////////////////////////////////
var dirs = [];
var parts = [];
//var container = document.createElement('div');
//document.body.appendChild( container );
var container = document.getElementById('header');
//document.body.appendChild( header );
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000)
camera.position.z = 1000;
var scene = new THREE.Scene();
function ExplodeAnimation(x, y) {
var geometry = new THREE.Geometry();
for (i = 0; i < totalObjects; i++) {
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = y;
vertex.z = 0;
geometry.vertices.push(vertex);
dirs.push({
x: (Math.random() * movementSpeed) - (movementSpeed / 2),
y: (Math.random() * movementSpeed) - (movementSpeed / 2),
z: (Math.random() * movementSpeed) - (movementSpeed / 2)
});
}
var material = new THREE.ParticleBasicMaterial({
size: objectSize,
color: color
});
var particles = new THREE.ParticleSystem(geometry, material);
this.object = particles;
this.status = true;
this.xDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.yDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.zDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
scene.add(this.object);
this.update = function() {
if (this.status == true) {
var pCount = totalObjects;
while (pCount--) {
var particle = this.object.geometry.vertices[pCount]
particle.y += dirs[pCount].y;
particle.x += dirs[pCount].x;
particle.z += dirs[pCount].z;
}
this.object.geometry.verticesNeedUpdate = true;
}
}
}
var renderer = new THREE.WebGLRenderer();
function render() {
requestAnimationFrame(render);
var pCount = parts.length;
while (pCount--) {
parts[pCount].update();
}
renderer.render(scene, camera);
}
window.addEventListener('mousedown', onclick, false);
window.addEventListener('resize', onWindowResize, false);
function onClick() {
event.preventDefault();
parts.push(new ExplodeAnimation((Math.random() * sizeRandomness) - (sizeRandomness / 2), (Math.random() * sizeRandomness) - (sizeRandomness / 2)));
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
document.getElementById("btn").addEventListener('click',run);
function run() {
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
<button id="btn">Click to run </button>
<div id="header">
I'm working on a Three.js project which you can find over here in its entirety.
As you can see, there is a substantial amount of vertical, unoccupied space surrounding the particles. I was wondering if it was possible to reduce that. If not, is it possible to put it inside a div? I tinkered around with renderer.setSize, but it also stretched the scene; meanwhile putting it inside a div did not produce any result for me.
Unfortunately, the formal training I received in regard to web design and development was scarce, only covering the basics and rudiments; thus, I had to try to understand things such as this online so I apologize if this sounds inane.
var SEPARATION = 70, AMOUNTX = 25, AMOUNTY = 20;
var container, camera, scene, renderer;
var particles, particle, count = 0;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
scene = new THREE.Scene();
particles = new Array();
var PI2 = Math.PI * 2;
var material = new THREE.SpriteCanvasMaterial( {
color: 0x333399,
program: function ( context ) {
context.beginPath();
context.arc( 0, 0, 0.5, 0, PI2, true );
context.fill();
}
} );
var i = 0;
for ( var ix = 0; ix < AMOUNTX; ix ++ ) {
for ( var iy = 0; iy < AMOUNTY; iy ++ ) {
particle = particles[ i ++ ] = new THREE.Sprite( material );
particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 );
particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 );
scene.add( particle );
}
}
renderer = new THREE.CanvasRenderer({alpha:true});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, 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;
mouseY = event.clientY - windowHalfY;
}
function onDocumentTouchStart( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
mouseY = event.touches[ 0 ].pageY - windowHalfY;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
mouseY = event.touches[ 0 ].pageY - windowHalfY;
}
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
var i = 0;
for ( var ix = 0; ix < AMOUNTX; ix ++ ) {
for ( var iy = 0; iy < AMOUNTY; iy ++ ) {
particle = particles[ i++ ];
particle.position.y = ( Math.sin( ( ix + count ) * 0.3 ) * 50 ) +
( Math.sin( ( iy + count ) * 0.5 ) * 50 );
particle.scale.x = particle.scale.y = ( Math.sin( ( ix + count ) * 0.3 ) + 1 ) * 4 +
( Math.sin( ( iy + count ) * 0.5 ) + 1 ) * 5;
}
}
renderer.render( scene, camera );
count += 0.1;
}
You can set a fixed height for you canvas and use it inside onWindowResize function and init function.
For example:
// set a fixed canvas height
var fixedCanvasHeight = 200;
function init(){
// give separation a new value for a better particle distribution
SEPARATION = window.innerWidth/AMOUNTX;
...
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / fixedCanvasHeight, 1, 10000 );
...
renderer.setSize( window.innerWidth, fixedCanvasHeight );
...
}
function onWindowResize() {
// give separation a new value for a better particle distribution
SEPARATION = window.innerWidth/AMOUNTX;
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / fixedCanvasHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, fixedCanvasHeight );
}
Is this what you're looking for? I've combined what cameraman and WestLangley were suggesting:
I used globalized WIDTH and HEIGHT variables
HEIGHT is a fixed value
Adjust camera.fov to zoom to fit what you want
var SEPARATION = 70,
AMOUNTX = 25,
AMOUNTY = 20,
// Globalized width & height varialbes
WIDTH = window.innerWidth, // width still references the window width
HEIGHT = 200; // height is now a fixed value (if this needs to be dynamic, you'll need to calculate it)
var container, camera, scene, renderer, particles, particle, count = 0;
var mouseX = 0,
mouseY = 0;
var windowHalfX = WIDTH / 2;
var windowHalfY = HEIGHT / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(35, WIDTH / HEIGHT, 1, 10000); // smaller FOV = tighter zoom
camera.position.z = 1000;
scene = new THREE.Scene();
particles = new Array();
var PI2 = Math.PI * 2;
var material = new THREE.SpriteCanvasMaterial({
color: 0x333399,
program: function(context) {
context.beginPath();
context.arc(0, 0, 0.5, 0, PI2, true);
context.fill();
}
});
var i = 0;
for (var ix = 0; ix < AMOUNTX; ix++) {
for (var iy = 0; iy < AMOUNTY; iy++) {
particle = particles[i++] = new THREE.Sprite(material);
particle.position.x = ix * SEPARATION - ((AMOUNTX * SEPARATION) / 2);
particle.position.z = iy * SEPARATION - ((AMOUNTY * SEPARATION) / 2);
scene.add(particle);
}
}
renderer = new THREE.CanvasRenderer({
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(WIDTH, HEIGHT);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = WIDTH / 2;
windowHalfY = HEIGHT / 2;
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
renderer.setSize(WIDTH, HEIGHT);
}
function onDocumentMouseMove(event) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
}
function onDocumentTouchStart(event) {
if (event.touches.length === 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - windowHalfX;
mouseY = event.touches[0].pageY - windowHalfY;
}
}
function onDocumentTouchMove(event) {
if (event.touches.length === 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - windowHalfX;
mouseY = event.touches[0].pageY - windowHalfY;
}
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var i = 0;
for (var ix = 0; ix < AMOUNTX; ix++) {
for (var iy = 0; iy < AMOUNTY; iy++) {
particle = particles[i++];
particle.position.y = (Math.sin((ix + count) * 0.3) * 50) +
(Math.sin((iy + count) * 0.5) * 50);
particle.scale.x = particle.scale.y = (Math.sin((ix + count) * 0.3) + 1) * 4 +
(Math.sin((iy + count) * 0.5) + 1) * 5;
}
}
renderer.render(scene, camera);
count += 0.1;
}
<script src="http://threejs.org/build/three.js"></script>
<script src="http://threejs.org/examples/js/renderers/CanvasRenderer.js"></script>
<script src="http://threejs.org/examples/js/renderers/Projector.js"></script>
As far as I understood your question, you have troubles putting the canvas into a div. Of course, within a div you can position and size the canvas much better.
Here the basic code snippets from your updated example: http://codepen.io/anon/pen/ybBVYX
var SCREEN_WIDTH, SCREEN_HEIGHT;
// init
container = $('.webgl');
SCREEN_WIDTH = container.width();
SCREEN_HEIGHT = container.height();
camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
camera.position.z = 1000;
renderer = new THREE.CanvasRenderer({alpha:true});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
container.append( renderer.domElement );
// resize
function onWindowResize() {
SCREEN_WIDTH = container.width();
SCREEN_HEIGHT = container.height();
camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
}
html, body {
color: #ff0000;
height: 100%;
}
.header {
height: 60%;
background-color: #ccc;
}
.webgl {
height: 40%;
}
<div class="header">
<p class="test">Hello</p>
Link
</div>
<div class="webgl"></div>
If you want to keep the aspect ratio, then you would need to set the width or height of your div and the canvas element explicitly, e.g. using jQuery:
SCREEN_WIDTH = container.width();
SCREEN_HEIGHT = SCREEN_WIDTH * aspectRatio;
container.height( SCREEN_HEIGHT );
I'm very new with JS and Pixi.js and I want some advices, Below is my example code. I want to know How to separate code to main.js, boss.js as function? I try but it's not work stage is show but boss that i draw not show so, I want to know how to. Thank you
var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer();
document.body.appendChild(renderer.view);
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var circle = new PIXI.Graphics();
var rect = new PIXI.Graphics();
var rectWidth = 160;
var rectHeight = 200;
var boss = new PIXI.Container();
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenWidth / 2) - (rectWidth / 2), (screenHeight / 2) - 60, rectWidth, rectHeight);
rect.endFill();
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenWidth / 2, (screenHeight / 2) - 140, 80);
circle.endFill();
boss.addChild(circle);
stage.addChild(boss);
stage.interactive = true;
renderer.view.style.position = "absolute";
renderer.view.style.display = "block";
renderer.autoResize = true;
renderer.resize(screenWidth, screenHeight);
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenWidth / 2) - (rectWidth / 2), (screenHeight / 2) - 60, 160, 200);
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenWidth / 2, (screenHeight / 2) - 140, 80);
boss.addChild(circle);
stage.addChild(boss);
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame( animate );
}
Here is an example of boss creation separated to it's own file and function:
http://plnkr.co/edit/43GgC3nPvFKEpflGhwvV?p=preview
main.js
document.addEventListener("DOMContentLoaded", function(event) {
var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer();
document.body.appendChild(renderer.view);
var screenSize = {
width: window.innerWidth,
height: window.innerHeight
}
var rectSize = {
width: 160,
height: 200
};
var boss = createBoss(screenSize, rectSize);
stage.addChild(boss);
stage.interactive = true;
renderer.view.style.position = "absolute";
renderer.view.style.display = "block";
renderer.autoResize = true;
renderer.resize(screenSize.width, screenSize.height);
boss = window.createBoss(screenSize, rectSize);
stage.addChild(boss);
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame( animate );
}
});
boss.js
function createBoss(screenSize, rectSize) {
var circle = new PIXI.Graphics();
var rect = new PIXI.Graphics();
var boss = new PIXI.Container();
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenSize.width / 2) - (rectSize.width / 2), (screenSize.height / 2) - 60, rectSize.width, rectSize.height);
rect.endFill();
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenSize.width / 2, (screenSize.height / 2) - 140, 80);
circle.endFill();
boss.addChild(circle);
return boss;
}