Background size is not scaling with viewport size - javascript

I have an issue with background size. Basically if you will change the viewport size of this page https://attiliosantomo.com/sfera the background is not following the viewport dimension, but it conserve previous viewport dimension and only if I refresh the page background will update to viewport size. Can someone help me? How would like my background follow viewport size by scaling his dimension.
<!doctype html>
<html>
<head>
<style>
#font-face{
font-family: Roslindale;
src: url("pvcweb-banner-TRIAL.woff") format('woff');
font-weight: bold;
}
.workspace {
height: 100vh;
width: 100vw;
top: 0;
left: 0;
display: grid;
place-items: center;
font: 700 12px system-ui;
}
body, html {
height: 100vh;
width: 100vw;
background-size: cover;
}
body{
overflow: hidden;
cursor: url(images/cursor.png),auto;
}
canvas {
width:100%; height:100%;
background-size: cover;
}
.header-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(0, 0, 0);
opacity: 0.1;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r122/three.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/gsap-latest-beta.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class='header-overla' style="position: fixed; height: 100vh;">
<script>
var mousePos = {x:.5,y:.5, z:.5};
document.addEventListener('mousemove', function (event) { mousePos = {x:event.clientX/window.innerWidth, y:event.clientY/window.innerHeight, z:event.clientZ/window.innerWidth};});
var phase = 0;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(95, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 30;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var boxSize = 0.2;
var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
var materialGreen = new THREE.MeshBasicMaterial({transparent: true, color: 0xffffff, opacity: 0.4, side: THREE.DoubleSide});
var pitchSegments = 60;
var elevationSegments = pitchSegments/2;
var particles = pitchSegments*elevationSegments
var side = Math.pow(particles, 1/3);
var radius = 30;
var parentContainer = new THREE.Object3D();
scene.add(parentContainer);
function posInBox(place) {
return ((place/side) - 0.5) * radius * 1.2;
}
//Plant the seeds, grow some trees in a grid!
for (var p = 0; p < pitchSegments; p++) {
var pitch = Math.PI * 2 * p / pitchSegments ;
for (var e = 0; e < elevationSegments; e++) {
var elevation = Math.PI * ((e / elevationSegments)-0.5)
var particle = new THREE.Mesh(geometry, materialGreen);
parentContainer.add(particle);
var dest = new THREE.Vector3();
dest.z = (Math.sin(pitch) * Math.cos(elevation)) * radius; //z pos in sphere
dest.x = (Math.cos(pitch) * Math.cos(elevation)) * radius; //x pos in sphere
dest.y = Math.sin(elevation) * radius; //y pos in sphere
particle.position.x = posInBox(parentContainer.children.length % side);
particle.position.y = posInBox(Math.floor(parentContainer.children.length/side) % side);
particle.position.z = posInBox(Math.floor(parentContainer.children.length/Math.pow(side,2)) % side);
console.log(side, parentContainer.children.length, particle.position.x, particle.position.y, particle.position.z)
particle.userData = {dests: [dest,particle.position.clone()], speed: new THREE.Vector3() };
}
}
function render() {
phase += 0.002;
for (var i = 0, l = parentContainer.children.length; i < l; i++) {
var particle = parentContainer.children[i];
var dest = particle.userData.dests[Math.floor(phase)%particle.userData.dests.length].clone();
var diff = dest.sub(particle.position);
particle.userData.speed.divideScalar(1.02); // Some drag on the speed
particle.userData.speed.add(diff.divideScalar(8000));// Modify speed by a fraction of the distance to the dest
particle.position.add(particle.userData.speed);
particle.lookAt(dest);
}
parentContainer.rotation.y = phase*3;
parentContainer.rotation.x = (mousePos.y-0.5) * Math.PI;
parentContainer.rotation.z = (mousePos.x-0.5) * Math.PI;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
</script>
</body>
</html>
Thank you so much

Your are using <canva> element with css (widht & height) inline, for your custom css you should use !important with size values
For <canva> element use object-fit instead of background-size
like this:
canvas {
width: 100% !important;
height: 100% !important;
object-fit: cover;
}
Sorry about my English, i dont know if i wrote correct

When you say "background" are you talking about the three.js scene?
If so, you need to add a resize event listener to resize the canvas/scene and update the camera.
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
You probaby also want to remove the default padding from the body with margin: '0px'

Related

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

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

Grabbing coordinates from render canvas instead of entire window

I'm experiencing a small problem with an editor I'm building. it's a terrain editor, with toolbars on the left and top, with a canvas on the bottom right. There is a beacon named 'helperHandle' in the canvas which will demonstrate which vector you are currently hovering over. however, the beacon doesn't align properly with the mouse, it seems to be using the entire window as an offset, instead of just the rendering canvas. as you can see from the image below. I've included my code below the image.
The javascript >>
$( document ).ready(function() {
var terrainMesh;
var helperHandle;
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var cameraholder;
function main() {
const canvas = document.querySelector('#terrainRender');
const renderer = new THREE.WebGLRenderer({canvas, alpha: true});
var cubes = [];
const fov = 40;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 1000;
cameraholder = new THREE.Object3D();
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0,10,20);
camera.lookAt( 0, 0, 0 );
camera.zoom = 0.5;
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0x555555 );
scene.add(cameraholder);
var size = 10;
var divisions = 10;
var gridHelper = new THREE.GridHelper( size, divisions );
scene.add( gridHelper );
var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
const color = 0xFFFFFF;
const intensity = 0.1;
light = new THREE.DirectionalLight(color, intensity);
light.position.set(1, 30, 10);
light.target.position.set( 0, 0, 0 );
light.castShadow = true;
var lightHelper = new THREE.DirectionalLightHelper( light, 5 );
scene.add( lightHelper );
const controls = new THREE.OrbitControls(camera, canvas);
controls.target.set(0, 0, 0);
controls.update();
scene.add( light );
var geometry = new THREE.PlaneBufferGeometry(60, 60, 9, 9);
var material = new THREE.MeshBasicMaterial(
{color: 0x666666,
side: THREE.DoubleSide
});
rotateObject(geometry, -90, 0, 0);
geometry.computeFaceNormals(); // needed for helper
var helperHandlegeometry = new THREE.ConeBufferGeometry( 1, 3, 3 );
helperHandlegeometry.rotateX( Math.PI / 2 );
helperHandle = new THREE.Mesh( helperHandlegeometry, new THREE.MeshNormalMaterial() );
scene.add( helperHandle );
terrainMesh = new THREE.Mesh( geometry, material );
scene.add( terrainMesh );
var wireframe = new THREE.WireframeGeometry( geometry );
var line = new THREE.LineSegments( wireframe );
line.material.depthTest = false;
line.material.opacity = 0.25;
line.material.transparent = true;
scene.add( line );
function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
const direction = (new THREE.Vector3())
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();
camera.near = boxSize / 100;
camera.far = boxSize * 100;
camera.updateProjectionMatrix();
camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
}
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = renderer.domElement.clientWidth;
const height = renderer.domElement.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = renderer.domElement.clientWidth / renderer.domElement.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
function onMouseMove( event ) {
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
terrainMesh.updateMatrixWorld();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObject( terrainMesh );
if ( intersects.length > 0 ) {
helperHandle.position.set( 0, 0, 0 );
helperHandle.lookAt( intersects[ 0 ].face.normal );
helperHandle.position.copy( intersects[ 0 ].point );
}
$('#coords').html(`X: ${mouse.x.toFixed(2)} <br>Y: ${mouse.y.toFixed(2)}`);
}
window.addEventListener( 'mousemove', onMouseMove, false );
requestAnimationFrame(render);
}
main();
});
The html >>
<div id="main">
<div id="toolBar">
</div>
<div class="editorWindow">
<div id="sideBar"></div>
<canvas id="terrainRender"></canvas>
<div id="coords"></div>
</div>
</div>
The CSS (less) >>
div{
}
body { margin: 0; }
#coords{
position: absolute;
top: 0;
width: 40px;
height: 40px;
background-color: #fff;
}
.titleBar{
height: 30px;
width: 100%;
display: block;
background-color: #e0e0e0;
}
#main{
position: relative;
background-color: #f4f4f4;
display: grid;
height: 99vh;
flex-wrap: wrap;
border: 1px solid #aaa;
padding: 0.2%;
.editorWindow{
flex: 1;
flex-direction: row;
display: flex;
}
#toolBar{
height: 60px;
}
#sideBar{
flex: 1 2 10%;
position: relative;
background-color: #f4f4f4;
border: solid 1px #aaa;
}
#terrainRender {
flex: 12 1 80%;
}
}
#terrain{
display: inline-block;
zoom: 100%;
transform-origin: center;
white-space: nowrap;
font-size: 0px;
transform-style: preserve-3d;
/*transform: rotateZ(0deg) rotateY(0deg) rotateX(45deg);*/
}

Three.js How to fit object to left half side of the screen(width and height)

After clicking the button, I want the whole 3D object(width and height) to fit to left side of the screen and show a div HTML info in the right side of the screen.
How to fit object to left side of the screen? Is it possible to set margin(px)?
var camera, scene, renderer;
var geometry, material, mesh;
var lookDirection = new THREE.Vector3();
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.mouseButtons = {
LEFT: THREE.MOUSE.RIGHT,
MIDDLE: THREE.MOUSE.MIDDLE,
RIGHT: THREE.MOUSE.LEFT
}
controls.enableZoom = false;
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
controls.update();
TWEEN.update();
}
function fit(){
controls.enabled = false;
var box = new THREE.Box3().setFromObject(mesh);
var boxSize = box.getSize(new THREE.Vector3()).length();
var boxCenter = box.getCenter(new THREE.Vector3());
var halfSizeToFitOnScreen = boxSize * 0.5;
var halfFovY = THREE.Math.degToRad(camera.fov * 0.5);
var distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
// compute a unit vector that points in the direction the camera is now
// in the xz plane from the center of the box
const direction = (new THREE.Vector3())
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();
// tween animation
var from = camera.position;
var to = direction.multiplyScalar(distance).add(boxCenter);
var tween = new TWEEN.Tween(from)
.to(to, 1000)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(this.x, this.y, this.z);
// update the Trackball controls to handle the new size
controls.enabled = true;
controls.target.copy(boxCenter);
controls.update();
})
.start();
}
document.getElementById("btn").addEventListener("click", fit);
body {
margin: 0;
overflow: hidden;
}
button {
position: fixed;
top: 0;
left: 0;
}
<button id="btn">Fit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://sole.github.io/tween.js/build/tween.min.js"></script>
Thanks!
Sounds like you're really just asking an HTML/JavaScript question
One way would be to use a flex box
function fit(){
const elem = document.querySelector('#panes> .right');
elem.style.display = elem.style.display == 'none' ? '' : 'none';
}
document.getElementById("btn").addEventListener("click", fit);
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
#panes {
display: flex;
width: 100vw;
height: 100vh;
}
#panes>.left,
#panes>.right {
flex: 1 1 50%;
height: 100%;
}
#panes>.left {
padding: 1em;
text-align: center;
background: red;
}
#panes>.right {
padding: 1em;
background: blue;
color: white;
}
button {
position: fixed;
top: 0;
left: 0;
}
<div id="panes">
<div class="left"> Stuff On Left</div>
<div class="right" style="display: none;">Stuff on right</div>
</div>
<button id="btn">Fit</button>
Then insert the canvas in the left pane and use a better example of how to set the canvas's size
var camera, scene, renderer;
var geometry, material, mesh;
var lookDirection = new THREE.Vector3();
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, 2, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
document.querySelector("#panes>.left").appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.mouseButtons = {
LEFT: THREE.MOUSE.RIGHT,
MIDDLE: THREE.MOUSE.MIDDLE,
RIGHT: THREE.MOUSE.LEFT
}
controls.enableZoom = false;
}
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function animate() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render( scene, camera );
controls.update();
TWEEN.update();
requestAnimationFrame( animate );
}
function fit(){
const elem = document.querySelector('#panes> .right');
elem.style.display = elem.style.display == 'none' ? '' : 'none';
}
document.getElementById("btn").addEventListener("click", fit);
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
#panes {
display: flex;
width: 100vw;
height: 100vh;
}
#panes>.left,
#panes>.right {
flex: 1 1 50%;
height: 100%;
}
#panes>.right {
padding: 1em;
background: blue;
color: white;
}
button {
position: fixed;
top: 0;
left: 0;
}
<div id="panes">
<div class="left"></div>
<div class="right" style="display: none;">Stuff on right</div>
</div>
<button id="btn">Fit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://sole.github.io/tween.js/build/tween.min.js"></script>
I hope it's not late to answer this question, but I found something that maybe is what you were looking for. Check Is there ANY way to have the three.js camera lookat being rendered off-center?
camera = new THREE.PerspectiveCamera( for, aspect, near, far );
camera.setViewOffset( fullWidth, fullHeight, widthOffset, heightOffset, viewWidth, viewHeight );
Take widthOffset and heightOffset as parameters to slide de target of your camera to any side.

Vanishing text into with css

I'm trying to make an Intro animation with some text for my personal website.
How can I add a text intro like this: https://codepen.io/nathanlong/pen/MyYqNd
over this css animation: https://codepen.io/gvrban/pen/rzNGpW
I've tried to copy/paste and merge the two pens but it doesn't work
I want the text to appear over the animation
Here is the code to the animation
var camera, scene, renderer;
var texture_placeholder,
isUserInteracting = false,
onMouseDownMouseX = 0,
onMouseDownMouseY = 0,
lon = 90,
onMouseDownLon = 0,
lat = 0,
onMouseDownLat = 0,
phi = 0,
theta = 0,
target = new THREE.Vector3();
init();
animate();
function init() {
var container, mesh;
container = document.getElementById('container');
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1100);
scene = new THREE.Scene();
texture_placeholder = document.createElement('canvas');
texture_placeholder.width = 128;
texture_placeholder.height = 128;
var context = texture_placeholder.getContext('2d');
context.fillStyle = 'rgb( 200, 200, 200 )';
context.fillRect(0, 0, texture_placeholder.width, texture_placeholder.height);
var materials = [
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space4.jpg'), // right
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space2.jpg'), // left
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space1.jpg'), // top
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space6.jpg'), // bottom
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space3.jpg'), // back
loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1037366/space5.jpg') // front
];
mesh = new THREE.Mesh(new THREE.BoxGeometry(300, 300, 300, 7, 7, 7), new THREE.MultiMaterial(materials));
mesh.scale.x = -1;
scene.add(mesh);
for (var i = 0, l = mesh.geometry.vertices.length; i < l; i++) {
var vertex = mesh.geometry.vertices[i];
vertex.normalize();
vertex.multiplyScalar(550);
}
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
//document.addEventListener( 'wheel', onDocumentMouseWheel, false );
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function loadTexture(path) {
var texture = new THREE.Texture(texture_placeholder);
var material = new THREE.MeshBasicMaterial({
map: texture,
overdraw: 0.5
});
var image = new Image();
image.onload = function() {
texture.image = this;
texture.needsUpdate = true;
};
image.src = path;
return material;
}
function onDocumentMouseDown(event) {
event.preventDefault();
isUserInteracting = true;
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
function onDocumentMouseMove(event) {
if (isUserInteracting === true) {
lon = (onPointerDownPointerX - event.clientX) * 0.1 + onPointerDownLon;
lat = (event.clientY - onPointerDownPointerY) * 0.1 + onPointerDownLat;
}
}
function onDocumentMouseUp(event) {
isUserInteracting = false;
}
// function onDocumentMouseWheel( event ) {
// camera.fov += event.deltaY * 0.05;
// camera.updateProjectionMatrix();
// }
function onDocumentTouchStart(event) {
if (event.touches.length == 1) {
event.preventDefault();
onPointerDownPointerX = event.touches[0].pageX;
onPointerDownPointerY = event.touches[0].pageY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
}
function onDocumentTouchMove(event) {
if (event.touches.length == 1) {
event.preventDefault();
lon = (onPointerDownPointerX - event.touches[0].pageX) * 0.1 + onPointerDownLon;
lat = (event.touches[0].pageY - onPointerDownPointerY) * 0.1 + onPointerDownLat;
}
}
function animate() {
requestAnimationFrame(animate);
update();
}
function update() {
if (isUserInteracting === false) {
lon += 0.1;
}
lat = Math.max(-85, Math.min(85, lat));
phi = THREE.Math.degToRad(90 - lat);
theta = THREE.Math.degToRad(lon);
target.x = 500 * Math.sin(phi) * Math.cos(theta);
target.y = 500 * Math.cos(phi);
target.z = 500 * Math.sin(phi) * Math.sin(theta);
camera.position.copy(target).negate();
camera.lookAt(target);
renderer.render(scene, camera);
}
html,
body {
margin: 0;
overflow: hidden;
}
img {
width: 8vw;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
<div id="container"></div>
<img src="https://s3-us-west-
2.amazonaws.com/s.cdpn.io/1037366/planet2.png">
I've merged both the codepens into one.
I've simply changed the class
.intro {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: black;
}
to
.intro {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: transparent;
z-index: 2;
}
When using position absolute, z-index is used to bring the object/element on top of each other (imagine a layered structure). Element with highest z-index will appear on the top of all elements with position set to absolute.
Here is more info on z-index.
Have look at this. Hope this is the desired output.

Auto-adjust canvas by itself in all possible sizes

I have one canvas-fx code ("stars" coming from deep to front, all centered, simulating space-navigation; it was not done by me) that I want to put in one website as a background.
I want it so that when a user resizes the window (dragging to right or left or resizing or whatever), the effect can auto-adjust itself so that the stars always come from the center in any size or even changing the desktop resolution (I refer the FX can auto-reset by itself the same it does when rendering the webcode).
Also I want it so that the code can adjust itself to the size of the content of the body (i.e. adding content from up to down, etc).
Finally, how can I quit the bottom bar, leaving only the scroll bar from the right?
Here is the complete code I am using:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>FX TEST</title>
<STYLE type="text/css">
html, body {
width:100%;
height:100%;
}
#Canvas2D {
position:absolute;
top:0;
left:0;
}
#content {
z-index: 10;
position: relative;
}
</STYLE>
<script language="JavaScript">
function setup() {
var fov = 150;
var SCREEN_WIDTH = 1920;
var SCREEN_HEIGHT = 1080;
var HALF_WIDTH = SCREEN_WIDTH / 2;
var HALF_HEIGHT = SCREEN_HEIGHT / 2;
var numPoints = 300;
function draw3Din2D(point3d) {
x3d = point3d[0];
y3d = point3d[1];
z3d = point3d[2];
var scale = fov / (fov + z3d);
var x2d = (x3d * scale) + HALF_WIDTH;
var y2d = (y3d * scale) + HALF_HEIGHT;
c.lineWidth = scale;
c.strokeStyle = "rgb(255,255,255)";
c.beginPath();
c.moveTo(x2d, y2d);
c.lineTo(x2d + scale, y2d);
c.stroke();
}
var canvas = document.getElementById('Canvas2D');
var c = canvas.getContext('2d');
var points = [];
function initPoints() {
for(i = 0; i < numPoints; i++) {
point = [(Math.random() * 400) - 200, (Math.random() * 400) - 200, (Math.random() * 400) - 200];
points.push(point);
}
}
function render() {
c.fillStyle = "rgb(0,0,0)";
c.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
for(i = 0; i < numPoints; i++) {
point3d = points[i];
z3d = point3d[2];
z3d -= 4;
if(z3d < -fov) z3d += 400;
point3d[2] = z3d;
draw3Din2D(point3d);
}
}
initPoints();
var loop = setInterval(function () {
render();
}, 50);
}
</script>
</head>
<body onload="setup();">
<canvas id="Canvas2D" width="1920" height="1080">NOT USING HTML5 SUPPORT</canvas>
<div id="content">
<z-index: 0></z-index:>
</div>
</body>
</html>
Live Demo
Full screen demo
Below are the modifications I made to make it work. First remove the size in your canvas element. Change it to
<canvas id="Canvas2D"></canvas>
Next here is what I use for my CSS when Im doing anything full screen with canvas.
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#Canvas2D {
position:absolute;
top:0;
left:0;
}
And here is the JS required to make it all work
// set the width and height to the full windows size
var SCREEN_WIDTH = window.innerWidth;
// Change to scroll height to make it the size of the document
var SCREEN_HEIGHT = document.documentElement.scrollHeight;
// Make sure to set the canvas to the screen height and width.
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
// everytime we resize change the height and width to the window size, and reset the
// center point
window.onresize = function () {
SCREEN_HEIGHT = canvas.height = document.documentElement.scrollHeight;
SCREEN_WIDTH = canvas.width = document.body.offsetWidth;
HALF_WIDTH = SCREEN_WIDTH / 2;
HALF_HEIGHT = SCREEN_HEIGHT / 2;
};
Well, first of all, thanks a lot to #Loktar for your inner support.
Now i had been working on the code that i will put in my own Official Website (relaunching it).
After the help of #Loktar, the problem was that the vertically autoadjust was not working, so i changed this :
var SCREEN_HEIGHT = document.documentElement.scrollHeight;
To this :
var SCREEN_HEIGHT = window.innerHeight;
And this :
SCREEN_HEIGHT = canvas.height = document.documentElement.scrollHeight;
Changed To this :
SCREEN_HEIGHT = canvas.height = document.body.offsetHeight;
Now it centers good vertically too.
The second problem was that when you doesn´t give to canvas command an exactly number of size it doesn´t show scrollbars, so i fund an style code that after i adadpt to this fx, the way now you can now have scrollbars horizontally and vertically. What you need to do is to add this to the style of your website :
div.scroll
{
width:100%;
height:100%;
overflow:scroll;
}
For after call it in the div of the content with a class, as you can see below :
<div id="content" class="scroll">
Now you will have scrollbars activated when needed. It was tested at Internet Explorer and Firefox and works. I hope it will help to apply to several other canvas codes.
Finally, here i left how the final code looks, and partially how it will look at my Official Website :
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>FX TEST</title>
<STYLE type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#Canvas2D {
position:absolute;
top:0;
left:0;
}
#content {
z-index: 10;
position: relative;
}
div.scroll
{
width:100%;
height:100%;
overflow:scroll;
}
</STYLE>
<script language="JavaScript">
function setup() {
var fov = 150;
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var HALF_WIDTH = SCREEN_WIDTH / 2;
var HALF_HEIGHT = SCREEN_HEIGHT / 2;
var numPoints = 300;
function draw3Din2D(point3d) {
x3d = point3d[0];
y3d = point3d[1];
z3d = point3d[2];
var scale = fov / (fov + z3d);
var x2d = (x3d * scale) + HALF_WIDTH;
var y2d = (y3d * scale) + HALF_HEIGHT;
c.lineWidth = scale;
c.strokeStyle = "rgb(255,255,255)";
c.beginPath();
c.moveTo(x2d, y2d);
c.lineTo(x2d + scale, y2d);
c.stroke();
}
var canvas = document.getElementById('Canvas2D');
var c = canvas.getContext('2d');
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
var points = [];
function initPoints() {
for (i = 0; i < numPoints; i++) {
point = [(Math.random() * 400) - 200, (Math.random() * 400) - 200, (Math.random() * 400) - 200];
points.push(point);
}
}
function render() {
c.fillStyle = "rgb(0,0,0)";
c.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
for (i = 0; i < numPoints; i++) {
point3d = points[i];
z3d = point3d[2];
z3d -= 4;
if (z3d < -fov) z3d += 400;
point3d[2] = z3d;
draw3Din2D(point3d);
}
}
initPoints();
var loop = setInterval(function () {
render();
}, 50);
window.onresize = function () {
SCREEN_HEIGHT = canvas.height = document.body.offsetHeight;
SCREEN_WIDTH = canvas.width = document.body.offsetWidth;
HALF_WIDTH = SCREEN_WIDTH / 2;
HALF_HEIGHT = SCREEN_HEIGHT / 2;
};
}
setup();
</script>
</head>
<body onload="setup();">
<canvas id="Canvas2D"></canvas>
<div id="content" class="scroll">
<z-index: 0>
</z-index:>
</div>
</body>
</html>
set the width and height of the canvas to 100%.

Categories

Resources