Animating Spiral in THREE.js
by nikakhachi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>
CSS
body {
margin: 0;
padding: 0;
overflow: hidden;
}
JavaScript
var camera, scene, renderer, geometry, mesh;
let x = 20;
let y = 0;
let z = 0;
let r = 20;
let tetha = 0;
const basicMaterial = new THREE.LineBasicMaterial({ linewidth: 1 })
const vertexMaterial = new THREE.LineBasicMaterial({ vertexColors: true });
const lastGraphicsData = {
coordinates: [],
objects: []
};
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x233231);
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500
scene.add(camera);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
drawLine();
renderer.render(scene, camera);
if(lastGraphicsData.coordinates.length >= 300){
replaceLinesWithBigLine()
}
}
function drawLine() {
const points = [];
points.push(new THREE.Vector3(x, y, z));
lastGraphicsData.coordinates.push(x, y, z);
const LINE_DISTANCE = 0.1;
r += LINE_DISTANCE;
x = r * Math.cos(tetha);
y = r * Math.sin(tetha);
tetha -= 0.1;
points.push(new THREE.Vector3(x, y, z));
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(geometry, basicMaterial);
scene.add(line);
lastGraphicsData.objects.push(line);
}
function replaceLinesWithBigLine() {
lastGraphicsData.objects.forEach((object) => {
object.geometry.dispose();
object.material.dispose();
scene.remove(object);
});
const geometry = new THREE.BufferGeometry();
geometry.addAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(lastGraphicsData.coordinates), 3)
);
const line = new THREE.Line(geometry, vertexMaterial);
scene.add(line);
lastGraphicsData.coordinates = [];
lastGraphicsData.objects = [];
}