Reputation: 11
This problem has been bothering me for the last few days. I really can't figure out how to add my three.js scene into a div, so I can use it as content on my website. I might have watched every video on youtube and read every post about this but I really cant figure it out. It would be very helpful if anybody could help me find a solution to this problem so I can finally have some peace.
This is my three.js code
<script src="three.js"></script>
<script type="module" src="GLTFLoader.js"></script>
<script src="OrbitControls.js"></script>
<script type="module">
import {GLTFLoader } from "./GLTFLoader.js"
var scene = new THREE.Scene();
scene.background = new THREE.Color(0xd3d2cd)
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
camera.position.set(1, 0.7, 1);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var loader = new GLTFLoader();
var obj;
loader.load("model.gltf", function (gltf) { obj = gltf.scene; scene.add(gltf.scene);});
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();
const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 2);
hemiLight.color.setHSL(197, 71, 73 );
hemiLight.groundColor.setHSL(197, 71, 73);
hemiLight.position.set( 0, 0, 0 );
scene.add( hemiLight );
const dirLight = new THREE.DirectionalLight( 0xfdfbd3, 1);
dirLight.color.setHSL(55, 95, 57);
dirLight.position.set( 0, 1.75, .5 );
dirLight.position.multiplyScalar( 20 );
scene.add( dirLight );
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
animate();
</script>
Just for your information, I'm a complete novice to javascript and programming languages as a whole, it has been only a few weeks since I have started to learn this stuff. So I would be very grateful if somebody could help me. Also English is not my first language, so I'm very sorry for my bad English.
Thank you. Twyn.
Upvotes: 1
Views: 1206
Reputation: 109
create a canvas in your html file
<canvas id="displayContent" style="width: 100% "></canvas>
Then get the canvas with querySelector or using getElementById method.
var canvas = document.querySelector('displayContent');
Then add this code block while you are craeting your renderer
const renderer = new THREE.WebGLRenderer({ canvas });
Upvotes: 2