create animation with zip of frame

This commit is contained in:
NekoVari 2024-12-17 17:36:53 +07:00
parent cad7c8f84e
commit 71e597158d
4 changed files with 45 additions and 51 deletions

View file

@ -5,13 +5,13 @@ const Animation = () => {
const [images, setImages] = useState([]);
const [currentFrame, setCurrentFrame] = useState(0);
const [loading, setLoading] = useState(true);
const frameRate = 100; // Frame rate in milliseconds
const frameRate = 60;
useEffect(() => {
const loadImages = async () => {
const zip = new JSZip();
try {
const response = await fetch('src/assets/characters/sprite.zip'); // Adjust the path to your ZIP file
const response = await fetch('src/assets/characters/M_Porsche_cross_arm.zip');
if (!response.ok) {
throw new Error('Network response was not ok');
}
@ -21,20 +21,27 @@ const Animation = () => {
const imgPromises = [];
zipContent.forEach((relativePath, file) => {
if (file.name.endsWith('.webp')) {
imgPromises.push(file.async('blob')); // Convert file to Blob
imgPromises.push(
file.async('base64').then(base64 => {
return `data:image/webp;base64,${base64}`;
})
);
}
});
const imgBlobs = await Promise.all(imgPromises);
const imgUrls = imgBlobs.map(blob => URL.createObjectURL(blob)); // Create object URLs
const imgUrls = await Promise.all(imgPromises);
console.log('Loaded images:', imgUrls); // Log the loaded image URLs
// console.log('Loaded images:', imgUrls);
if (imgUrls.length === 0) {
console.error('No images found in the ZIP file.');
}
setImages(imgUrls);
} catch (error) {
console.error('Error loading images:', error);
} finally {
setLoading(false); // Set loading to false after images are loaded
setLoading(false);
}
};
@ -43,31 +50,28 @@ const Animation = () => {
}, []);
useEffect(() => {
const interval = setInterval(() => {
setCurrentFrame((prevFrame) => (prevFrame + 1) % images.length);
}, frameRate);
if (images.length > 0) {
const interval = setInterval(() => {
setCurrentFrame((prevFrame) => (prevFrame + 1) % images.length);
}, frameRate);
return () => clearInterval(interval);
}, [images]);
useEffect(() => {
// Cleanup object URLs when the component unmounts
return () => {
images.forEach(url => URL.revokeObjectURL(url)); // Clean up object URLs
};
return () => clearInterval(interval);
}
}, [images]);
if (loading) {
return <div>Loading...</div>; // Show loading indicator
return <div>Loading...</div>;
} else {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{images.length > 0 && (
{images.length > 0 ? (
<img
src={images[currentFrame]}
alt="Animation frame"
style={{ maxWidth: '100%', height: 'auto' }} // Responsive image
alt={`Animation frame ${currentFrame + 1}`}
style={{ maxWidth: '500px', height: 'auto' }}
/>
) : (
<div>No images to display.</div>
)}
</div>
);