首页 > 解决方案 > 如何将三个 js 对象居中到 DIV 中:

问题描述

我无法将三个 js 对象居中到 DIV

这是我的代码

    import * as THREE from 'https://cdn.skypack.dev/pin/three@v0.128.0-iDyvDZdRCoyR9DXa2rWg/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();

这就是问题的样子:

在此处输入图像描述

刚刚超出 DIV 的对象:

在此处输入图像描述

我不知道为什么会这样。我试图解决这个问题几天并尝试了很多方法,但它仍然不起作用。可能我不明白的东西,需要你的帮助......

标签: javascriptthree.js

解决方案


我想我解决了这个问题。我只是删除了css中#canvas的填充,它现在可以按预期工作。

现在这就是它的样子:


推荐阅读