Creating an interactable interpolated fractal pattern based on draggable lines in Three.js is an exciting project! To achieve this, we'll build upon your existing draggable line implementation and introduce a recursive structure to generate fractal lines up to a specified rank. Here's a step-by-step guide along with the complete code to help you accomplish this.
Overview
-
Data Structures:
- Point: Represents a draggable point in 2D space.
- FractalLine: Represents a line segment that can generate child lines based on fractal rules.
-
Fractal Generation:
- For each
FractalLine, generate child lines according to the fractal rules you've defined.
- Recursive generation allows the fractal to grow to the desired rank.
-
Interactivity:
- Users can drag any point, and all connected lines update accordingly.
- Lines will reflect changes in real-time, maintaining the fractal structure.
-
Rendering:
- Each
FractalLine is a THREE.Line object added to the scene.
- Points are represented as small
THREE.Mesh spheres for better interactivity.
Implementation Steps
1. Define Classes for Points and Lines
We'll create two classes: Point for draggable points and FractalLine for lines that can generate child lines.
// Point Class
class Point {
constructor(x, y, scene, onDrag) {
const geometry = new THREE.SphereGeometry(2, 16, 16);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
this.mesh = new THREE.Mesh(geometry, material);
this.mesh.position.set(x, y, 0);
scene.add(this.mesh);
this.onDrag = onDrag;
}
setPosition(x, y) {
this.mesh.position.set(x, y, 0);
}
getPosition() {
return this.mesh.position.clone();
}
// Highlight the point when selected
highlight() {
this.mesh.material.color.set(0x00ff00);
}
// Remove highlight
unhighlight() {
this.mesh.material.color.set(0xff0000);
}
}
// FractalLine Class
class FractalLine {
constructor(startPoint, endPoint, scene, rank, maxRank) {
this.startPoint = startPoint;
this.endPoint = endPoint;
this.scene = scene;
this.rank = rank;
this.maxRank = maxRank;
this.children = [];
const material = new THREE.LineBasicMaterial({ color: 0xffffff });
const geometry = new THREE.BufferGeometry().setFromPoints([
this.startPoint.getPosition(),
this.endPoint.getPosition(),
]);
this.line = new THREE.Line(geometry, material);
this.line.userData = this; // Reference to this FractalLine
this.line.frustumCulled = false;
scene.add(this.line);
// Generate child lines if not at max rank
if (this.rank < this.maxRank) {
this.generateChildren();
}
}
generateChildren() {
const start = this.startPoint.getPosition();
const end = this.endPoint.getPosition();
// Calculate intermediate points
const leftX = start.x + (end.x - start.x) / 3;
const leftY = start.y + (end.y - start.y) / 2;
const rightX = end.x - (end.x - start.x) / 3;
const rightY = end.y - (end.y - start.y) / 2;
// Create new points
const leftPoint = new Point(leftX, leftY, this.scene, () => {
this.update();
});
const rightPoint = new Point(rightX, rightY, this.scene, () => {
this.update();
});
// Create child lines
const leftLine = new FractalLine(this.startPoint, leftPoint, this.scene, this.rank + 1, this.maxRank);
const middleLine = new FractalLine(leftPoint, rightPoint, this.scene, this.rank + 1, this.maxRank);
const rightLine = new FractalLine(rightPoint, this.endPoint, this.scene, this.rank + 1, this.maxRank);
this.children.push(leftLine, middleLine, rightLine);
}
update() {
// Update the main line geometry
this.line.geometry.setFromPoints([
this.startPoint.getPosition(),
this.endPoint.getPosition(),
]);
this.line.geometry.attributes.position.needsUpdate = true;
// Update child lines recursively
this.children.forEach(child => child.update());
}
dispose() {
// Remove lines and points from the scene
this.scene.remove(this.line);
this.children.forEach(child => child.dispose());
if (this.startPoint.mesh.parent === this.scene) {
this.scene.remove(this.startPoint.mesh);
}
if (this.endPoint.mesh.parent === this.scene) {
this.scene.remove(this.endPoint.mesh);
}
}
}
2. Initialize the Fractal
We'll create an initial FractalLine which will recursively generate child lines up to the specified rank.
// Parameters
const MAX_RANK = 2; // Change this to increase/decrease fractal depth
// Create initial points
const pointA = new Point(-50, 0, scene, () => {
fractal.update();
});
const pointB = new Point(50, 0, scene, () => {
fractal.update();
});
// Create the initial fractal line
const fractal = new FractalLine(pointA, pointB, scene, 1, MAX_RANK);
3. Update the Dragging Logic
We'll modify the dragging logic to allow dragging any point in the fractal. When a point is dragged, all connected lines update accordingly.
// Variables for dragging
let selectedPoint = null;
let isDragging = false;
// Mouse down event
function onMouseDown(event) {
event.preventDefault();
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
// Collect all point meshes
const pointMeshes = [];
function collectPointMeshes(fractalLine) {
pointMeshes.push(fractalLine.startPoint.mesh);
fractalLine.children.forEach(child => collectPointMeshes(child));
}
collectPointMeshes(fractal);
const intersects = raycaster.intersectObjects(pointMeshes);
if (intersects.length > 0) {
selectedPoint = intersects[0].object;
selectedPoint.userData = intersects[0].object; // Optional: store reference
isDragging = true;
// Highlight the selected point
fractal.children.forEach(child => {
child.startPoint.unhighlight();
child.endPoint.unhighlight();
});
selectedPoint.material.color.set(0x0000ff);
} else {
isDragging = false;
}
}
// Mouse move event
function onMouseMove(event) {
if (!isDragging || !selectedPoint) return;
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersect = new THREE.Vector3();
raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), intersect);
if (intersect) {
selectedPoint.position.x = intersect.x;
selectedPoint.position.y = intersect.y;
fractal.update();
}
}
// Mouse up event
function onMouseUp(event) {
if (selectedPoint) {
// Remove highlight
selectedPoint.material.color.set(0xff0000);
}
selectedPoint = null;
isDragging = false;
}
// Add event listeners
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
4. Full Modified Code
Here's the complete HTML file integrating all the above components. This example sets the fractal depth to 2 (rank 2), but you can adjust the MAX_RANK variable to increase or decrease the fractal's complexity.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js Interactive Fractal</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r136/three.module.min.js';
// --- Classes ---
// Point Class
class Point {
constructor(x, y, scene, onDrag) {
const geometry = new THREE.SphereGeometry(2, 16, 16);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
this.mesh = new THREE.Mesh(geometry, material);
this.mesh.position.set(x, y, 0);
scene.add(this.mesh);
this.onDrag = onDrag;
}
setPosition(x, y) {
this.mesh.position.set(x, y, 0);
}
getPosition() {
return this.mesh.position.clone();
}
// Highlight the point when selected
highlight() {
this.mesh.material.color.set(0x00ff00);
}
// Remove highlight
unhighlight() {
this.mesh.material.color.set(0xff0000);
}
}
// FractalLine Class
class FractalLine {
constructor(startPoint, endPoint, scene, rank, maxRank) {
this.startPoint = startPoint;
this.endPoint = endPoint;
this.scene = scene;
this.rank = rank;
this.maxRank = maxRank;
this.children = [];
const material = new THREE.LineBasicMaterial({ color: 0xffffff });
const geometry = new THREE.BufferGeometry().setFromPoints([
this.startPoint.getPosition(),
this.endPoint.getPosition(),
]);
this.line = new THREE.Line(geometry, material);
this.line.userData = this; // Reference to this FractalLine
this.line.frustumCulled = false;
scene.add(this.line);
// Generate child lines if not at max rank
if (this.rank < this.maxRank) {
this.generateChildren();
}
}
generateChildren() {
const start = this.startPoint.getPosition();
const end = this.endPoint.getPosition();
// Calculate intermediate points
const leftX = start.x + (end.x - start.x) / 3;
const leftY = start.y + (end.y - start.y) / 2;
const rightX = end.x - (end.x - start.x) / 3;
const rightY = end.y - (end.y - start.y) / 2;
// Create new points
const leftPoint = new Point(leftX, leftY, this.scene, () => {
this.update();
});
const rightPoint = new Point(rightX, rightY, this.scene, () => {
this.update();
});
// Create child lines
const leftLine = new FractalLine(this.startPoint, leftPoint, this.scene, this.rank + 1, this.maxRank);
const middleLine = new FractalLine(leftPoint, rightPoint, this.scene, this.rank + 1, this.maxRank);
const rightLine = new FractalLine(rightPoint, this.endPoint, this.scene, this.rank + 1, this.maxRank);
this.children.push(leftLine, middleLine, rightLine);
}
update() {
// Update the main line geometry
this.line.geometry.setFromPoints([
this.startPoint.getPosition(),
this.endPoint.getPosition(),
]);
this.line.geometry.attributes.position.needsUpdate = true;
// Update child lines recursively
this.children.forEach(child => child.update());
}
dispose() {
// Remove lines and points from the scene
this.scene.remove(this.line);
this.children.forEach(child => child.dispose());
if (this.startPoint.mesh.parent === this.scene) {
this.scene.remove(this.startPoint.mesh);
}
if (this.endPoint.mesh.parent === this.scene) {
this.scene.remove(this.endPoint.mesh);
}
}
}
// --- Three.js Setup ---
// Scene setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
// Camera setup
const aspectRatio = window.innerWidth / window.innerHeight;
const cameraSize = 200;
const camera = new THREE.OrthographicCamera(
-cameraSize * aspectRatio,
cameraSize * aspectRatio,
cameraSize,
-cameraSize,
1,
1000
);
camera.position.set(0, 0, 500);
camera.lookAt(0, 0, 0);
// Renderer setup
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Raycaster and mouse vector
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Zoom logic (same as original)
const zoomSpeed = 0.8;
function onWheel(event) {
event.preventDefault();
const rect = renderer.domElement.getBoundingClientRect();
const mouseX = ((event.clientX - rect.left) / rect.width) * 2 - 1;
const mouseY = -((event.clientY - rect.top) / rect.height) * 2 + 1;
const mouseWorld = new THREE.Vector3(mouseX, mouseY, 0).unproject(camera);
const zoomFactor = 1 - event.deltaY * 0.001 * zoomSpeed;
const ctrlPressed = event.ctrlKey;
const shiftPressed = event.shiftKey;
if (ctrlPressed) {
camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x;
camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x;
} else if (shiftPressed) {
camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y;
camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y;
} else {
camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x;
camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x;
camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y;
camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y;
}
camera.updateProjectionMatrix();
}
// Prevent default browser behavior for wheel scrolling with Control or Shift key
window.addEventListener('wheel', onWheel, { passive: false });
// Prevent default context menu on right-click
window.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
// Handle window resize
function onWindowResize() {
const aspect = window.innerWidth / window.innerHeight;
camera.left = -cameraSize * aspect;
camera.right = cameraSize * aspect;
camera.top = cameraSize;
camera.bottom = -cameraSize;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize);
// --- Fractal Initialization ---
const MAX_RANK = 2; // Set desired fractal depth
// Create initial points
const pointA = new Point(-50, 0, scene, () => {
fractal.update();
});
const pointB = new Point(50, 0, scene, () => {
fractal.update();
});
// Create the initial fractal line
const fractal = new FractalLine(pointA, pointB, scene, 1, MAX_RANK);
// --- Dragging Logic ---
// Variables for dragging
let selectedPoint = null;
let isDragging = false;
// Mouse down event
function onMouseDown(event) {
event.preventDefault();
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
// Collect all point meshes
const pointMeshes = [];
function collectPointMeshes(fractalLine) {
pointMeshes.push(fractalLine.startPoint.mesh);
pointMeshes.push(fractalLine.endPoint.mesh);
fractalLine.children.forEach(child => collectPointMeshes(child));
}
collectPointMeshes(fractal);
const intersects = raycaster.intersectObjects(pointMeshes);
if (intersects.length > 0) {
selectedPoint = intersects[0].object;
isDragging = true;
// Highlight the selected point
fractal.children.forEach(child => {
child.startPoint.unhighlight();
child.endPoint.unhighlight();
});
selectedPoint.material.color.set(0x0000ff);
} else {
isDragging = false;
}
}
// Mouse move event
function onMouseMove(event) {
if (!isDragging || !selectedPoint) return;
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersect = new THREE.Vector3();
raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), intersect);
if (intersect) {
selectedPoint.position.x = intersect.x;
selectedPoint.position.y = intersect.y;
fractal.update();
}
}
// Mouse up event
function onMouseUp(event) {
if (selectedPoint) {
// Remove highlight
selectedPoint.material.color.set(0xff0000);
}
selectedPoint = null;
isDragging = false;
}
// Add event listeners
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
// --- Render Loop ---
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
Explanation
-
Classes:
- Point: Represents control points in the fractal. Each point is a small red sphere that can be dragged. When selected, it turns blue.
- FractalLine: Represents a line segment between two points. If the current rank is less than the maximum rank, it generates child lines based on your fractal rules.
-
Fractal Generation:
- The
FractalLine class recursively generates child lines by calculating intermediate points (leftPoint and rightPoint) based on the parent line's geometry.
- These child lines are instances of
FractalLine themselves, allowing the fractal to expand recursively.
-
Interactivity:
- When a user clicks on a point, it becomes selected and highlighted (changes color to blue).
- As the user drags the mouse, the selected point's position updates, and all connected lines regenerate to reflect the new geometry.
- Releasing the mouse button deselects the point and removes the highlight.
-
Rendering:
- All lines and points are added to the Three.js scene.
- The render loop continuously renders the scene, ensuring real-time updates as users interact with the fractal.
-
Customization:
- Fractal Depth: Adjust the
MAX_RANK variable to increase or decrease the depth of the fractal. Be cautious with higher depths, as they increase the number of lines exponentially.
- Styling: You can customize the appearance of points and lines by modifying their materials.
Extending the Fractal
To extend the fractal to higher ranks, simply increase the MAX_RANK variable. However, keep in mind that the number of lines and points grows exponentially with each additional rank, which can impact performance.
const MAX_RANK = 3; // For a deeper fractal
Handling Complexity
For higher fractal ranks, managing and interacting with numerous points and lines can become challenging. Here are some suggestions to manage complexity:
- Grouping: Use
THREE.Group to group related lines and points, making it easier to manage transformations.
- Performance Optimization: Consider optimizing rendering by reducing the number of line segments or using
THREE.InstancedMesh for repeated elements.
- User Interface: Implement UI controls to allow users to toggle visibility of different fractal ranks or reset the fractal.
Conclusion
By structuring your fractal using recursive classes and leveraging Three.js's powerful rendering and interactivity features, you can create a dynamic and interactive fractal pattern. Users can intuitively explore the fractal by dragging points, witnessing real-time updates to the intricate structure. Feel free to experiment with different fractal rules, depth levels, and interactive features to customize the experience further.