I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation.
The issue arises when the screen size is adjusted - as it becomes smaller, the canvas and object scale down accordingly, which functions as intended. However, upon resizing the screen to a larger size, the canvas extends and takes up the entire page.
I am seeking a solution to maintain consistent dimensions for both width and height of the canvas regardless of the screen size.
Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset= UFT-8>
<title>tema</title>
<style type="text/css">
div{
width: 50%;
margin-left: 20px;
margin-right: 100px;
margin-top: 20px;
margin-bottom: 20px;
border: 2px solid blue;
}
</style>
</head>
<body>
<section class="menu">
<div id="container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js" ></script>
<script type="text/javascript">
function init(){
width = 500;
height = 500;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, width/height, 0.1, 1000 );
camera.position.z = 500;
renderer = new THREE.WebGLRenderer();
renderer.setSize( width, height);
renderer.setClearColor( 0xffffff);
renderer.setPixelRatio( window.devicePixelRatio );
contenedor = document.getElementById('container');
contenedor.appendChild(renderer.domElement);
var obj = new THREE.CubeGeometry(100,100,100);
var material = new THREE.MeshNormalMaterial();
body = new THREE.Mesh(obj,material);
scene.add( body );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth/ window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
var animate = function () {
requestAnimationFrame( animate );
body.rotation.x+=0.01;
body.rotation.y+=0.01;
renderer.render(scene, camera);
};
init();
animate();
</script>
</section>
</body>
</html>