To add interactivity to your webpage, you can easily create an HTML element and link it to a JavaScript function for the "onclick" event. Below is a quick example using a button (but feel free to use a different element like a link):
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rotate Mesh On Button Clicked</title>
</head>
<body>
<button onclick="myFunction()">Rotate</button>
<script type="text/javascript" src="three.min.js"></script>
<script type="text/javascript" src="OrbitControls.js"></script>
<script type="text/javascript" src="scene.js"></script>
</body>
</html>
JavaScript
var container, camera, scene, renderer;
var geometry, material, mesh;
var cameraControls;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xdbdbdb );
container.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 3, 0.5, 40 );
scene.add( camera );
// controls
cameraControls = new THREE.OrbitControls( camera, renderer.domElement );
// lights
scene.add( new THREE.AmbientLight( 0x222222 ) );
var light = new THREE.PointLight( 0xffffff, 0.8 );
camera.add( light );
// objects
geometry = new THREE.CylinderGeometry( 5, 5, 5, 5 );
material = new THREE.MeshPhongMaterial( {color: 0x00aafa} );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
window.addEventListener( 'resize', onWindowResize, false );
}
function myFunction() {
mesh.rotateX(90);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
cameraControls.update();
}
function render() {
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
In this code snippet, clicking the button triggers the "myFunction" which rotates the Mesh by 90°, demonstrating a simple interactive feature.