Hii everyone I have created a django project and a separate three.js project using vanilla js. How do I integrate three.js in my django?
I have researched but couldn’t find any resource for that.
Please help me integrating three.js and Django.
Thanks in advance
There’s not really any special technique here. You integrate three.js in Django the same way you would any other JaveScript.
For example, if you include this script (taken from this example) inside a page template, it will create a <canvas>
element showing a spinning box and add it to the page:
<script type="module">
import * as THREE from 'https://cdn.skypack.dev/three';
let camera, scene, renderer;
let mesh;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 400;
scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry( 200, 200, 200 );
const material = new THREE.MeshBasicMaterial( { color: "red" } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
mesh.rotation.x += 0.005;
mesh.rotation.y += 0.01;
renderer.render( scene, camera );
}
</script>
If you don’t see anything, check the browser console and also try adjusting your CSS to make sure the canvas is visible. The canvas is added to the document.body
in this line:
document.body.appendChild( renderer.domElement );
where do I need to add? in which file?
document.body.appendChild( renderer.domElement );
It sounds like you need to understand Django better. We can’t help you with that here, have you tried following the official Django tutorials? If that doesn’t help, then please post your question on a Django forum.
on the html body create a canvas element like this:
on your script replace this lines:
renderer = new THREE.WebGLRenderer( { antialias: true } );
document.body.appendChild( renderer.domElement );
with:
var canvas = document.querySelector(“#myCanvas”)
renderer = new THREE.WebGLRenderer({ canvas})
This allows you to place the canvas element anywhere on the DOM
When I used this code and ran the website and inspected it says “TypeError: THREE.PerspectiveCamera is not a constructor” not sure if I’m using the wrong installation of three js or what …
edit: it was the wrong version, using the most recent version from three - npm fixed the problem.