My goal is to create a straightforward animation using three.js, HTML, and CSS. The concept involves generating multiple BoxGeometries within a for loop and adjusting the rotation of each box incrementally with each iteration. I have successfully achieved this technique.
Below is my implementation in the main.js file:
import './style.css'
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
//Initialize Camera and Set Position
const camera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 0.01, 1000);
camera.position.setZ(0);
camera.position.setX(32);
camera.position.setY(0);
//Create Scene
const scene = new THREE.Scene();
//Initialize Renderer
const renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true} );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );
//Initialize OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
//Initialize Light
const pointLight = new THREE.PointLight(0xfffff, 1);
pointLight.position.set( 1000, 1000, 1000);
scene.add(pointLight);
//Intro cube init
//This loop generates multiple rotating Box meshes
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00, wireframe: false} );
for(var i = 0; i < 16; i++){
const cube = new THREE.Mesh( geometry, material );
cube.position.x = i * 2
cube.rotation.x = i * .05
cube.scale.x = .1
scene.add( cube );
}
//HTML button event listener
var start_button = document.getElementById("begin-animation");
start_button.addEventListener("click", startButton);
function startButton(){
camera.position.x -= 5;
}
// animation
function animation() {
controls.update()
renderer.render( scene, camera );
}
This is how my index.html file looks:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Site</title>
</head>
<body>
<canvas id="bg"></canvas>
<div class="container">
<button id="begin-animation" class="begin-animation" value="False">Begin</button>
</div>
<script type="module" src="/main.js"></script>
</body>
</html>
And here is my style.css file:
...
The challenge I face is ensuring that the camera.position.x
only triggers when the "begin-animation" button is clicked once to start the animation. Moving this function to the main animation()
results in an immediate action before the button is pressed. How can I achieve the same effect but tied to the button click?
I have attached an image illustrating the desired outcome (Note: the star marks the initial camera position facing the first mesh while showing the full view of every subsequent mesh): https://i.sstatic.net/NKWz6.jpg