I have been following an online tutorial for three.js that results in a spinning 3D cube. I have used the following JavaScript inside a script file:
function spin() {
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth/2, window.innerHeight/2);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial( { color: 0xffff00});
var cube = new THREE.Mesh(geometry, material);
camera.position.z = 5;
scene.add(cube);
var render = function(){
requestAnimationFrame(render);
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
}
Currently, this generates a spinning yellow cube on a black background. I can see that it is possible to change the size of the canvas (using renderer.setSize()), but is it possible to reposition it on the page (or add other styling such as transparent backgroud)? e.g. fit it around other elements.
I thought that it might be possible to create my own canvas and create the cube on this canvas, instead of using the one generated by three.js, would this be possible?
Both ways are possible, both using CSS (for static style) or JS (for dynamic style changes). In the end, it's just a canvas element and you can access it like any other element.
You can pass in your own canvas to the renderer like this:
new THREE.WebGLRenderer({ canvas: myCanvasElement });
where myCanvasElement
is the element reference, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With