Hello there,
Sorry to bother with what seems to be a very basic question, yet I’ve been struggling to find a solution to my problem…
So, basically I’m trying to load my animation script in the head of my html file (as it seems to be a common practice (?)) and render that animation in a canvas element with a given id attribute by passing it to the renderer’s constructor.
Here’s my html file:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My first three.js app</title> <style> body { margin: 0; } canvas { display: block; } </style> <script src="js/three.min.js"></script> <script src="js/main.js"></script> </head> <body> <canvas id="myCanvasId"></canvas> </body> </html>
and my js/main.js file:
var myCanvas = document.getElementById("myCanvasId")
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer({antialias: true, canvas: myCanvas});
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
var animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
However, this doesn’t work. It returns a TypeError ‘v is null’ (and it seems to me that v is the dom element passed to the renderer’s constructor)…
Also I am not sure of two things:
- Do I still have to run document.body.appendChild( renderer.domElement ) since I am adding the canvas element explicitly in the html file ?
- Does the call to the render method (ie the animate function) have to be made in the body ?
In case you are wondering, I am fairly new to JS and HTML so some guidance and best practices would be very much appreciated !!!