Anthony R
Anthony R

Reputation: 23

Move a three js canvas inside a div tag

I'm an absolute beginner.

I've created a 3d model in blender, and I'm trying to build a portfolio website to show off some of my work. I followed a tutorial online to and I've gotten to the point where I can display my .gltf model in a canvas sized the way I want it. I just can get seem to place it inside a div tag.

Here is my section of code:

<div class="model">
    Model should go here:
    <script src="three.min.js"></script>
    <script src="GLTFLoader.js"></script>
    <script src="OrbitControls.js"></script>
    <script>
        let scene, camera, render


        function init() {

            scene = new THREE.Scene()
            scene.background = new THREE.Color(0xdddddd)

            camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 5000)
            camera.rotation.y = 45 / 180 * Math.PI
            camera.position.x = 18
            camera.position.y = 18
            camera.position.z = 18



            hlight = new THREE.AmbientLight(0x404040, 5)
            scene.add(hlight)

            renderer = new THREE.WebGLRenderer({ antialias: true })
            renderer.setSize(1024, 567)

            controls = new THREE.OrbitControls(camera, renderer.domElement);
            document.body.appendChild(renderer.domElement)

            let loader = new THREE.GLTFLoader()
            loader.load('patiomk2.gltf', function (gltf) {
                car = gltf.scene.children[0]
                car.scale.set(1000, 1000, 1000)
                scene.add(gltf.scene)
                animate();

            })
        }

        function animate() {
            renderer.render(scene, camera);
            requestAnimationFrame(animate);
        }
        init()
    </script>

</div>

And here is what appears in Chrome when I inspect the element

I want the canvas to appear in the div highlighted in green, but it is throwing it at the end of the body shown in yellow.

From what I've read online, it may have something to do with this line of code appending the canvas to the end of the body. Removing that line breaks everything, and I'm not sure what to do as a substitute.

document.body.appendChild(renderer.domElement)

Any tips or guidance would be appreciated. Thanks.

Upvotes: 2

Views: 2111

Answers (1)

Mugen87
Mugen87

Reputation: 31026

Give your div an ID, query it and then append the renderer's canvas to it like so:

const div = document.getElementById('myDiv');
div.appendChild(renderer.domElement);

You have to be aware to execute this code when the DOM is ready. Otherwise it won't be possible to query the container element. Hence, I suggest you move your script tags below the closing </body> tag.

Upvotes: 2

Related Questions