Exploring the world of THREE.js library has led me to attempt creating a particle sphere within my React App. Drawing inspiration from this project, I've made some progress but seem to have hit a roadblock.
Strangely, despite similarities in code - except for updating deprecated methods - whenever I try to render with THREE, an odd straight line appears every time.
Even after spending hours poring over the documentation and trying to understand each method of this component, confusion still reigns supreme.
This is what I currently have (for a live experience click here):
let camera;
let renderer;
let scene;
const vector3D = new THREE.Vector3();
// Fetch canvas constraints.
const getConstraints = () => {
const canvas = document.getElementById("canvas");
const { width, height } = canvas.getBoundingClientRect();
// Determine canvas width and height - defaulting to computed constraints.
return [canvas.width ?? width, canvas.height ?? height];
};
// Retrieve random point within sphere for particle placement.
const getRandomPointInSphere = radius => {
const x = THREE.MathUtils.randFloat(-1, 1);
const y = THREE.MathUtils.randFloat(-1, 1);
const z = THREE.MathUtils.randFloat(-1, 1);
const normaliseRatio = 1 / Math.sqrt(x * x + y * y + z * z);
vector3D.x = x * normaliseRatio * radius;
vector3D.y = y * normaliseRatio * radius;
vector3D.z = z * normaliseRatio * radius;
return vector3D;
};
// Initialize methods.
const initScene = () => {
const [canvasWidth, canvasHeight] = getConstraints();
// Renderer setup.
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("canvas"),
antialias: true, alpha: true,
});
renderer.setSize(canvasWidth, canvasHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Scene setup.
scene = new THREE.Scene();
// Camera setup.
camera = new THREE.PerspectiveCamera(45, canvasWidth, canvasHeight, 1, 1000);
camera.position.set(100, 0, 100);
};
const initPoints = () => {
const geometry = new THREE.BufferGeometry();
const positions = [];
const particleSize = 0.2;
const particleColor = 0x1826e0; // Dark blue
const particleCount = 50000 / (particleSize * 10);
for(let i = 0; i < particleCount; i++){
let vertex = getRandomPointInSphere(50);
positions.push(vertex.x, vertex.y, vertex.z);
}
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({ size: particleSize, color: particleColor });
const particles = new THREE.Points(geometry, material);
scene.add(particles);
};
initScene();
initPoints();
renderer.render(scene, camera);
Being fairly new to THREE (and canvases overall), any assistance is greatly welcomed.