movax100movbx20mul
movax100movbx20mul

Reputation: 117

How to center three js object into DIV:

I cannot center three js object into DIV

Here is my code:

    import * as THREE from 'https://cdn.skypack.dev/pin/[email protected]/mode=imports,min/optimized/three.js';
     
    const container = document.getElementById("canvas");
    // const selected = document.querySelector("#canvas");
    // document.body.appendChild(container);
    
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( container.offsetWidth, container.offsetWidth );
    
    // renderer.setSize( item.clientWidth, item.clientHeight );
    
    container.appendChild( renderer.domElement );
    
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    const cube = new THREE.Mesh( geometry, material );
    scene.add( cube );
    
    camera.position.z = 5;
    
    const animate = function () {
        requestAnimationFrame( animate );
    
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
    
        renderer.render( scene, camera );
    };
    
    animate();

And that's how the problem looks:

enter image description here

Object just going outside the DIV:

enter image description here

I dont know why it happens. I'm trying to fix this a couple of days and try a lot of ways and it still does not work. Probably I don't understand something and need your help...

Upvotes: 1

Views: 356

Answers (1)

movax100movbx20mul
movax100movbx20mul

Reputation: 117

I guess i solved the problem. I just delete padding of the #canvas in css and its now work as expected.

now thats how it looks like:

Upvotes: 1

Related Questions