Load 3D Model into Container dynamically via Dropwdown \ JS - javascript

Loading this model (example) here seems to nlt work the way I want.
I execute a JS and fill the "var" with an url
that url is in the container to render the 3d model aswell...
Sadly the container-ed script will not take the new var at all it seems.
(if the url is present in script directly it worksy but I want to swap out the model dynamically
<style>
.dropbtn {
background-color: #04AA6D;color: white;padding: 16px;font-size: 16px;border: none;
}
.dropdown {
position: relative;display: inline-block;
}
.dropdown-content {
display: none;position: absolute;background-color: #f1f1f1;min-width: 160px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1;
}
.dropdown-content a {
color: black;padding: 12px 16px;text-decoration: none;display: block;
}
.dropdown-content a:hover {background-color: #ddd;}
.dropdown:hover .dropdown-content {display: block;}
.dropdown:hover .dropbtn {background-color: #3e8e41;}
</style>
</head>
<body>
<div class="dropdown">
<button class="dropbtn">Model</button>
<div class="dropdown-content">
Model
Model2
</div>
</div>
</body>
<canvas id="scene"></canvas>
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/OBJLoader.js'></script>
<script>
//This demo is using the plugin "OBJLoader". Don't forget to include it into your page ;)
//You can find it here : https://github.com/mrdoob/three.js/tree/cf584a60bdfd24c42eaa81d484533364742bda44/examples/js/loaders
var renderer, scene, camera, banana;
var ww = window.innerWidth,
wh = window.innerHeight;
function init(){
renderer = new THREE.WebGLRenderer({canvas : document.getElementById('scene')});
renderer.setSize(ww,wh);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50,ww/wh, 0.1, 10000 );
camera.position.set(0,0,500);
scene.add(camera);
//Add a light in the scene
directionalLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
directionalLight.position.set( 0, 0, 350 );
directionalLight.lookAt(new THREE.Vector3(0,0,0));
scene.add( directionalLight );
//Load the obj file
loadOBJ();
}
var loadOBJ = function(){
//Manager from ThreeJs to track a loader and its status
var manager = new THREE.LoadingManager();
//Loader for Obj from Three.js
var loader = new THREE.OBJLoader( manager );
//Launch loading of the obj file, addBananaInScene is the callback when it's ready
loader.load( '$model', addBananaInScene);
};
var addBananaInScene = function(object){
banana = object;
//Move the banana in the scene
banana.rotation.x = Math.PI/2;
banana.position.y = -200;
banana.position.z = 50;
//Go through all children of the loaded object and search for a Mesh
object.traverse( function ( child ) {
//This allow us to check if the children is an instance of the Mesh constructor
if(child instanceof THREE.Mesh){
child.material.color = new THREE.Color(0X00FF00);
//Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
child.geometry.computeVertexNormals();
}
});
//Add the 3D object in the scene
scene.add(banana);
render();
};
var render = function () {
requestAnimationFrame(render);
//Turn the banana
banana.rotation.z += .01;
renderer.render(scene, camera);
};
init();
</script>
I tried to pass the url for the model via javascript

Related

In three.js does not work material selection through span

At first, span worked for me, then I set up materialsLib and initMaterialSelectionMenus from documentation and examples, but now or the span does not work, then the model does not appear.
Help, please!
UPD
The problem was in the functions. Apparently they were looped or something like that.
Some of code
main.html:
<canvas id="c" width="100" height="100" allowtransparency frameborder="no" scrolling="yes"</canvas>
<div id="menu">
<div></div>
<span>Kar color: <select id="kar-mat"></select></span><br/><br/>
<span>Prof color: <select id="pro-mat"></select></span>
</div>
<style>
#c {width: 100px; height: 100px; display: block;}
#menu {position: absolute; left: 1em; top: 1em; padding: 1em; background: rgba(0, 0, 0, 0.8); color: white; font-family: monospace;}
</style>
<script type="module" src="./main.js"></script>
main.js:
var karMatSelect = document.getElementById( 'kar-mat' );
var proMatSelect = document.getElementById( 'pro-mat' );
var objParts = {
karkass: [],
proff: [],
};
...
function loadModel() {
var LOADER = new GLTFLoader();
LOADER.crossOrigin = true;
LOADER.load('1.glb',
(gltf) => {
console.log('loading complete')
const objbox = gltf.scene;
SCENE.add(objbox);
console.log(objbox);
objParts.karkass.push(objbox.getObjectByName('karkasidver')); //all objects are [Mesh]es
objParts.proff.push(objbox.getObjectByName( 'profl' ),);
...
function initMaterials() {
materialsLib = {
karkaslib: [
new THREE.MeshStandardMaterial( {
color: 0x154889, metalness: 1, roughness: 0.2, name: '5005'
} ),
.....
proflib: [
......
} ),
],
};
}
function initMaterialSelectionMenus() {
function addOption(name, menu) {
var option = document.createElement( 'option' );
option.text = name;
option.value = name;
menu.add(option);
}
materialsLib.karkaslib.forEach( function ( material ) {
addOption(material.name, karMatSelect);
} );
materialsLib.proflib.forEach( function ( material ) {
addOption(material.name, proMatSelect);
} );
karMatSelect.selectedIndex = 2;
proMatSelect.selectedIndex = 5;
karMatSelect.addEventListener( 'change', updateMaterials );
proMatSelect.addEventListener( 'change', updateMaterials );
}
function updateMaterials() {
initMaterials()
var karkasMat = materialsLib.karkaslib[karMatSelect.selectedIndex];
var proflMat = materialsLib.karkaslib[proMatSelect.selectedIndex];
objParts.karkass.forEach(part => part.material = karkasMat);
objParts.proff.forEach(part => part.material = proflMat);
}
When I started the project, I had errors in the console. I made a few changes to fix it:
In loadModel I have add rows with initMaterials(); and initMaterialSelectionMenus();
objParts.karkass.push(objbox.getObjectByName('karkasidver'));
objParts.proff.push(objbox.getObjectByName('profl'));
console.log(dumpObject(objbox).join('\n')); //-список объектов в сцене
/* Add function call for initialization*/
initMaterials();
updateMaterials();
/* Add function call for UI initialization*/
initMaterialSelectionMenus();
I have add checks for undefined for karkasMat and proflMat in the function updateMaterials. Also I have removed call initMaterials().
function updateMaterials() {
/* Remove call for initMaterials() */
var karkasMat = materialsLib.karkaslib[karMatSelect.selectedIndex];
var proflMat = materialsLib.karkaslib[proMatSelect.selectedIndex];
/* added check for empty element */
if (karkasMat) {
objParts.karkass.forEach(part => part.material = karkasMat);
}
/* added check for empty element */
if (proflMat) {
objParts.proff.forEach(part => part.material = proflMat);
}
}
3.
function updateCamera() {
CAMERA.updateProjectionMatrix();
/* Remove next rows, because animation function already started, and will update controls and render scene*/
// CONTROLS.update();
// RENDERER.render(SCENE, CAMERA);
// animate()
}
Result
Alex has an error:
in function updateMaterials()
var proflMat = materialsLib.karkaslib[proMatSelect.selectedIndex];
instead of
var proflMat = materialsLib.proflib[proMatSelect.selectedIndex];

three.js: Adding and replacing objects in scene

I am trying out the following using three.js, where I have 2 shapes: “squares” and a “sphere”.
Each object has a button associated with it. If the user clicks a button, the corresponding shape will be added to the scene however, there can only be 1 square and 1 sphere in a scene at any one time.
If the user adds a new square, it should replace the old one. I seem to be having trouble achieving this though with my code below. Currently, I can successfully add the square and sphere objects however, when I click to add another square, the current square doesn’t get replaced.
Please advise, thank you!
<html>
<head>
<title>My second three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<button id="button1">Square1</button>
<button id="button2">Square2</button>
<button id="button3">Sphere</button>
<script src="js/three.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
loader.load( ‘square1.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button1").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( ‘square2.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button2").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( ‘sphere.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
sphere = node;
sphere.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button3").addEventListener("click", function(){
scene.add(sphere);
});
});
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
Consider tracking the "current square" shape outside the scope of your <button> click handlers, to ensure that the logic for adding and removing these shape from the scene functions as expected.
Specifically, you'll want to call scene.remove() with the current square shape (if present), rather than to call it with the shape object that you subsequently call scene.add() with:
/* Current code */
document.getElementById("button1").addEventListener("click", function(){
scene.remove(square); /* You're removing the square object here, */
scene.add(square); /* and then adding the same square object to the scene */
});
You might find it useful to adapt your script as follows:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
/*
Not sure where you get your loader object from
*/
var loader = ''; // ??
/*
Add this to track current shapes
*/
var currentSquare = '';
var currentSphere = '';
/*
Define a general, reusable method for loading geometry
*/
function loadShape(filename, onLoaded) {
loader.load( filename, function ( geometry ) {
var foundMesh = '';
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
foundMesh = node;
foundMesh.material.map.anisotropy = maxAnisotropy;
}
});
if(foundMesh) {
onLoaded(foundMesh)
}
}
}
/*
Use the general loader method defined above
*/
loadShape('square1.glb', function(nextSquare) {
document.getElementById("button1").addEventListener("click", function(){
/*
If current square exists, remove it
*/
if(currentSquare) {
scene.remove(currentSquare);
}
/*
Add the square for the button just clicked
and update currentSquare
*/
scene.add(nextSquare);
currentSquare = nextSquare;
});
})
loadShape('square2.glb', function(nextSquare) {
document.getElementById("button2").addEventListener("click", function(){
if(currentSquare) {
scene.remove(currentSquare);
}
scene.add(nextSquare);
currentSquare = nextSquare;
});
})
loadShape('sphere.glb', function(nextSphere) {
document.getElementById("button3").addEventListener("click", function(){
if(currentSphere) {
scene.remove(currentSphere);
}
scene.add(nextSphere);
currentSphere = nextSphere;
});
})
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
Hope this helps!

place a three.js sceen inside bootstrap grid

I try to understand how to embed three.js scene with few toggles inside of a bootstrap grid, for some reason my canvas which is inside column refuse to be in same row with the text column and i cant figure out why, any help will be much appreciated.
Preview: https://htmlpreview.github.io/?https://github.com/Phoreaka/PlateInGrid/blob/master/index.html
Html:
<section id="intro">
<div class="container-fluid">
<div class="row">
<div class="col-lg-4 col-md-4 textContainer ">
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>
</div> <!-- col end -->
<div class="col-lg-8 col-md-8">
<div id="myCanvas"></div>
<button id="polychrome"></button>
<button id="blue"></button>
<button id='PausePlay'>Pause</button>
</div> <!-- col end --->
</div> <!--row end -->
</div> <!-- container end -->
</section>
Css:
html, body {
direction: rtl;
font-family: 'Heebo', sans-serif;
-webkit-font-smoothing: antialiased;
margin: 0px;
overflow: hidden;
}
.background {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: -99;
background-color: lightgray;
background-repeat: no-repeat;
background-size: cover;
}
#intro {
width: 100wh;
height: 100%;
}
.textContainer {
height: auto;
font-size: 22px;
}
#myCanvas {
}
canvas {
height: 0;
}
#polychrome {
background-color: rgba(246, 244, 231, 1);
border-radius: 50%;
width: 20px;
height: 20px;
bottom: 20px;
border: 2px solid #194E9F;
}
#blue {
background-color: rgba(246, 244, 231, 1);
border-radius: 50%;
width: 20px;
height: 20px;
bottom: 20px;
border: 2px solid #194E9F;
}
#PausePlay {
background-color: transparent;
bottom: 20px;
border-style: none;
}
Javascript:
var container, stats, plate, plateTwo;
//loading objects into scene
var camera, scene, renderer, plate, plateTwo, controls; //loading objects into scene
canvas_width = 700,
canvas_height = 700;
//Pause button toggle-Boolean for start and restart
var initAnim = true;
var runAnim = false;
var isPlay = true;
//tweening
init();
animate();
//init functions for all the scene
function init() {
container = document.getElementById( 'myCanvas' ); //creates div and inside of it canvas
document.body.appendChild( container );
// scene
scene = new THREE.Scene();
//camera
camera = new THREE.PerspectiveCamera( 40,canvas_width / canvas_height, 100, 100000 );
camera.position.set( 0, 0, 1000 );
//lights
var ambient = new THREE.AmbientLight( 0xFFFFf3, 1.1 );
ambient.position.set( 0, 0, 900 ).normalize();
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.6 );
directionalLight.position.set( 0, 0, 700 ).normalize();
scene.add( directionalLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.6 );
directionalLight.position.set( 0, 0, -700 ).normalize();
scene.add( directionalLight );
//lights end
//setting renderer
renderer = new THREE.WebGLRenderer({
alpha: true});//background opacity
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( canvas_width, canvas_height );
document.body.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
//setting render end
//orbit controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target = new THREE.Vector3(-300,0,0);
controls.minPolarAngle = 1; // radians
controls.maxPolarAngle = Math.PI/2; // radians
controls.minDistance = 500;
controls.maxDistance = 800;
controls.enablePan = false;
//orbit controls end
// model blue
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); //helper for texture loading
//texture loader
var mtlLoader = new THREE.MTLLoader();
mtlLoader.crossOrigin = ''; //cross origin-allows to run it on github
mtlLoader.setPath( 'images/new/' );
mtlLoader.load( 'BluePlate.mtl', function( materials ) {
materials.preload();
//model loader
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'images/new/' );
objLoader.load( 'BluePlate.obj', addPlate);
});
//object position setings
var addPlate = function(object){
plate = object;
plate.name = 'blue_plate';
//Move the plate in the scene
plate.rotateX(0);
plate.rotateY(0);
plate.rotateZ(30);
plate.position.x = -300;
plate.position.y = 0;
plate.position.z = 0;
plate.scale.y = 1.8;
plate.scale.x = 1.8;
plate.scale.z = 1.8;
//Add the 3D object in the scene
scene.add(plate);//adds the plate
animate(plate);
render();
};
//model blue end
//model Polychrome inside of button function appears only when "#polychrome is pressed"
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); //helper for texture loading
//texture loader
var mtlLoaderTwo = new THREE.MTLLoader();
mtlLoaderTwo.crossOrigin = ''; //cross origin-allows to run it on github
mtlLoaderTwo.setPath( 'images/new/' );
mtlLoaderTwo.load( 'PolychromePlate.mtl', function( materials ) {
materials.preload();
//model loader
var objLoaderTwo = new THREE.OBJLoader();
objLoaderTwo.setMaterials( materials );
objLoaderTwo.setPath( 'images/new/' );
objLoaderTwo.load( 'PolychromePlate.obj', addPlateTwo);
});
//object position setings
var addPlateTwo = function(object){
plateTwo = object;
plateTwo.name = "color_plate";
//Move the plate in the scene
plateTwo.rotateX(0);
plateTwo.rotateY(0);
plateTwo.rotateZ(30);
plateTwo.position.x = -300;
plateTwo.position.y = 0;
plateTwo.position.z = 0;
plateTwo.scale.y = 1.8;
plateTwo.scale.x = 1.8;
plateTwo.scale.z = 1.8;
}
//polychrome model end
//Add the 3D object in the scene
var changeTexture = function(){
if(!(scene.getObjectByName('color_plate')))
{
scene.remove(plate);//removes the blue plate from scene
scene.add(plateTwo);
animate(plateTwo);
render();
}
};
//function for button blue to switch back to blue texture
function changeTextureBlue(){
if(!(scene.getObjectByName('blue_plate')))
{
scene.add(plate);
scene.remove(plateTwo);//removes the polychrome
}
}
//mouse click - running the functions of button click need to appear after the model load
document.getElementById('polychrome').addEventListener('click', changeTexture, false);
document.getElementById('blue').addEventListener('click', changeTextureBlue, false);
//mouse click end
//pause toggle
var startButton = document.getElementById( 'PausePlay' );
// Start Button
startButton.onclick = function StartAnimation() {
// Start and Pause
if (runAnim) {
startButton.innerHTML = 'Pause';
runAnim = false;
isPlay = true;
animate();
} else {
startButton.innerHTML = 'Play';
runAnim = true;
isPlay = false;
}
}//pause toggle end
} // init ends
//settings for window resize
function onWindowResize() {
camera.aspect = canvas_width / canvas_height;
camera.updateProjectionMatrix();
renderer.setSize( canvas_width, canvas_height );
} //window resize settings end
//animate function
function animate() {
if (!isPlay) return;
requestAnimationFrame(animate);
if ( plate !== undefined) {
plate.rotation.y += -.001;
};
if ( plateTwo !== undefined ) {
plateTwo.rotation.y += -.001;
};
render();
controls.update();
} //animate function end
//render
function render() {
renderer.render( scene, camera );
} //render end
You are not adding your renderer to the div.
you have this:
container = document.getElementById( 'myCanvas' );
document.body.appendChild( container );
// then later..
document.body.appendChild( renderer.domElement );
You code is...
getting a reference to myCanvas,
Moving myCanvas div to be the last element in the body,
Then adding the renderer canvas as the last element in the body (which will be after the myCanvas div).
What you probably want it this:
// Get a reference to the container div
container = document.getElementById( 'myCanvas' );
// Add the renderer.domElement, which is a canvas, to the container div.
container.appendChild( renderer.domElement );

How to move a PIXI DisplayObject?

I have the following files( using last PIXI.js version):
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>pixi.js example 1</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000000;
width:100%;
height:100%;
}
canvas {
display:block;
}
</style>
<script src="js/pixi.js"></script>
<script src="js/XALUI/XALUI.js"></script>
<script src="js/XALUI/Button.js"></script>
</head>
<body>
<script>
// create an new instance of a pixi stage
var stage = new PIXI.Stage(0x66FF99);
// create a renderer instance
var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);
// add the renderer view element to the DOM
document.body.appendChild(renderer.view);
requestAnimFrame( animate );
// create a texture from an image path
var texture = PIXI.Texture.fromImage("bunny.png");
// XALUI
var button = new XALUI.Button(texture);
stage.addChild(button);
function animate() {
button.position.x = button.position.x + 20;
// render the stage
renderer.render(stage);
requestAnimFrame( animate );
}
</script>
</body>
</html>
js/XALUI/Button.js
XALUI.Button = function(texture) {
PIXI.DisplayObject.call(this);
this._button = new PIXI.Sprite(texture);
}
XALUI.Button.prototype = Object.create(PIXI.DisplayObject.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
XALUI.Button.prototype._renderWebGL = function(renderSession) {
this._button._renderWebGL(renderSession);
}
XALUI.Button.prototype._renderCanvas = function(renderSession) {
this._button._renderCanvas(renderSession);
};
How can I move my button to another position or to an another initial position? I have tried setting the position.x:
var button = new XALUI.Button(texture);
button.position.x = 100;
And also tried to set the position of the sprite:
this._button = new PIXI.Sprite(texture);
this._button.position.x = 100;
But it doesn't work. Please help.
The problem lies in that you're attaching and moving XALUI.Button instead of the inner PIXI.Sprite. Setting the position on the inner sprite (this._button.position.x) would only work if you had added that PIXI.Sprite to the stage. Since DisplayObjects do not contain multiple DisplayObjects, the stage has no reference to the actual sprite. There are a couple of ways to fix this. First, you could inherit from PIXI.Sprite
XALUI.Button = function(texture) {
PIXI.Sprite.call(this, texture);
};
XALUI.Button.prototype = Object.create(PIXI.Sprite.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
Or to have it inherit from DisplayObjectContainer in the same manner as above but that implies a button will hold multiple graphical objects so do what works best for you. Here's a working example of the first approach.
var XALUI = {};
// Inherits from PIXI.Sprite
XALUI.Button = function(texture) {
PIXI.Sprite.call(this, texture);
};
XALUI.Button.prototype = Object.create(PIXI.Sprite.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
// Prepare the stage
var stage = new PIXI.Stage(0x66FF99);
var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);
var texture = PIXI.Texture.fromImage("http://www.goodboydigital.com/pixijs/examples/1/bunny.png");
var button = new XALUI.Button(texture);
document.body.appendChild(renderer.view);
requestAnimationFrame(animate);
stage.addChild(button);
// Animate the button
function animate() {
button.position.x = button.position.x + 5;
if (button.position.x > window.innerWidth + button.width) {
button.position.x = -button.width;
}
renderer.render(stage);
requestAnimationFrame(animate);
}
<script src="https://cdn.rawgit.com/GoodBoyDigital/pixi.js/v2.0.0/bin/pixi.js"></script>

Positioning the three.js container as an html div

I have an article container which has three aside tags inside it. The third aside element id='menuPuzzleType' contains a Three.js script which makes two cube meshes, and renders them in a Canvas renderer.
<article id="popup">
<aside id='close'><img src="img/close.png" onClick="aFunction()" /></aside>
<aside id='msgPuzzleType'>Please choose the puzzle type you want to play</aside>
<aside id='menuPuzzleType'>
<script>
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
cube.rotation.y -= 0.03;
cube2.rotation.y -=0.03;
renderer2.render(scene2, camera2);
}
var container2 = document.getElementById('menuPuzzleType');
//renderer
var renderer2 = new THREE.CanvasRenderer();
renderer2.setSize(400,400);//Was 100,100
container2.appendChild(renderer2.domElement);
//Scene
var scene2 = new THREE.Scene();
//Camera
var camera2 = new THREE.PerspectiveCamera(50,50/50,1,1000);
camera2.position.z = 240;//normal value is 100
camera2.position.y=60;
scene2.add(camera2);
//Axes
var axes2= new THREE.AxisHelper();
//Add texture for the cube
//Use image as texture
var img2 = new THREE.MeshBasicMaterial({ //CHANGED to MeshBasicMaterial
map:THREE.ImageUtils.loadTexture('img/2d.png')
});
img2.map.needsUpdate = true; //ADDED
//Add Cube
var cube = new THREE.Mesh(new THREE.CubeGeometry(40,40,40),img2);
cube.position.x =- 60;
scene2.add(cube);
var img3 = new THREE.MeshBasicMaterial({ //CHANGED to MeshBasicMaterial
map:THREE.ImageUtils.loadTexture('img/3d.png')
});
img3.map.needsUpdate = true; //ADDED
var cube2 = new THREE.Mesh(new THREE.CubeGeometry(40,40,40),img3);
cube2.position.x = 70; cube.position.y = 60; cube2.position.y=60;
scene2.add(cube2);
renderer2.render(scene2,camera2);
animate();
</script>
</aside>
</article>
I need to put the two cubes into the article container tag.
Here is my css code:
body{ overflow:hidden; }
article {
border:solid 1px #00CC33;
width:420px;
height:200px;
font-family: baskerville;
font-size: 16px;
margin-top: 50px;
/*For IE9 compatibility*/
behavior: url(border-radius.htc);
border-radius: 8px;
position:relative;
}
#popup {
bottom:50%;
position:relative;
margin: 0px;
left:30%;
}
#msgPuzzleType{ margin-left:60px; }
img{
behavior: url(border-radius.htc);
border-radius: 8px;
position:relative;
}
#menuPuzzleType{
background-color:#999999;
border:solid 1px #3300CC;
height:200px;
}
How can I move two cubes into the article container tag?
A "Three.js" solution to your problem is to do this:
renderer2.setSize( 400, 150 );
You also have hardwired the aspect ratio of your PerspectiveCamera, so you need to make it match the canvas dimensions.
var camera2 = new THREE.PerspectiveCamera( 50, 400/150, 1, 1000 );
This will make the canvas smaller so it fits. You then can move the camera closer so your objects are of the size you want.
Using your link provided, i changed the following to put the cubes into the article:
canvas {
position: absolute;
top: -80px;
}

Categories