Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
wheattoast11 committed Nov 30, 2024
1 parent 1da28aa commit 635e48f
Showing 1 changed file with 53 additions and 20 deletions.
73 changes: 53 additions & 20 deletions src/components/Canvas.jsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,63 @@
import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { Scene } from './Scene';
import { Scene } from '../three/Scene';

function Canvas() {
const containerRef = useRef(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const [scene, setScene] = useState(null);

// Handle resize
useEffect(() => {
// Only initialize if container exists
if (!containerRef.current) return;

// Wait for next frame to ensure DOM measurements are accurate
requestAnimationFrame(() => {
try {
const newScene = new Scene(containerRef.current);
setScene(newScene);

return () => {
if (newScene) {
newScene.dispose();
}
};
} catch (error) {
console.error('Error initializing scene:', error);
const handleResize = () => {
if (containerRef.current) {
setDimensions({
width: containerRef.current.clientWidth,
height: containerRef.current.clientHeight
});
}
});
};

// Initial size
handleResize();

window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);

// Initialize scene
useEffect(() => {
if (!containerRef.current || dimensions.width === 0 || dimensions.height === 0) {
return;
}

try {
const newScene = new Scene(containerRef.current, dimensions);
setScene(prev => {
if (prev) {
prev.dispose();
}
return newScene;
});

// Start animation
const animate = () => {
if (newScene) {
newScene.animate();
}
requestAnimationFrame(animate);
};
animate();

return () => {
if (newScene) {
newScene.dispose();
}
};
} catch (error) {
console.error('Error initializing scene:', error);
}
}, [dimensions]);

return (
<div
ref={containerRef}
Expand All @@ -37,8 +68,10 @@ function Canvas() {
width: '100%',
height: '100%',
zIndex: -1,
background: '#000000'
background: '#000000',
overflow: 'hidden'
}}
aria-hidden="true"
/>
);
}
Expand Down

0 comments on commit 635e48f

Please sign in to comment.