60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
// composables/useCanvasInitialization.ts
|
|
import { ref, nextTick, type Ref } from 'vue';
|
|
import { type CellSize, type AnimationState } from '@/application/types';
|
|
|
|
export function useCanvasInitialization(animation: Ref<AnimationState>, cellSize: CellSize) {
|
|
const animCanvas = ref<HTMLCanvasElement | null>(null);
|
|
|
|
const initializeCanvas = async (): Promise<boolean> => {
|
|
// Wait for the next tick to ensure the canvas element is rendered
|
|
await nextTick();
|
|
|
|
if (!animCanvas.value) {
|
|
console.error('PreviewModal: Animation canvas not found');
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const context = animCanvas.value.getContext('2d');
|
|
if (!context) {
|
|
console.error('PreviewModal: Failed to get 2D context from animation canvas');
|
|
return false;
|
|
}
|
|
|
|
animation.value.canvas = animCanvas.value;
|
|
animation.value.ctx = context;
|
|
return true;
|
|
} catch (error) {
|
|
console.error('PreviewModal: Error initializing animation canvas:', error);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const updateCanvasSize = () => {
|
|
if (!animCanvas.value) {
|
|
console.warn('PreviewModal: Cannot update canvas size - canvas not found');
|
|
return;
|
|
}
|
|
|
|
// More robust check for valid cell dimensions
|
|
if (cellSize && typeof cellSize.width === 'number' && typeof cellSize.height === 'number' && cellSize.width > 0 && cellSize.height > 0) {
|
|
animCanvas.value.width = cellSize.width;
|
|
animCanvas.value.height = cellSize.height;
|
|
} else {
|
|
console.warn('PreviewModal: Cannot update canvas size - invalid cell dimensions', cellSize ? `width: ${cellSize.width}, height: ${cellSize.height}` : 'cellSize is undefined');
|
|
|
|
// Set a default minimum size to prevent rendering errors
|
|
if (animCanvas.value.width === 0 || animCanvas.value.height === 0) {
|
|
animCanvas.value.width = animCanvas.value.width || 100;
|
|
animCanvas.value.height = animCanvas.value.height || 100;
|
|
}
|
|
}
|
|
};
|
|
|
|
return {
|
|
animCanvas,
|
|
initializeCanvas,
|
|
updateCanvasSize,
|
|
};
|
|
}
|