| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- export const MIN_CANVAS_SCALE = 0.1
- export const MAX_CANVAS_SCALE = 4
- export const CANVAS_SCALE_STEP = 0.1
- export type CanvasScaleDirection = 'in' | 'out'
- export interface FitCanvasOptions {
- viewportWidth: number
- viewportHeight: number
- canvasWidth: number
- canvasHeight: number
- padding?: Partial<{
- top: number
- right: number
- bottom: number
- left: number
- }>
- }
- export const normalizeCanvasScale = (scale: number) => {
- const safeScale = Number.isFinite(scale) ? scale : 1
- const clampedScale = Math.min(MAX_CANVAS_SCALE, Math.max(MIN_CANVAS_SCALE, safeScale))
- return Math.round(clampedScale * 100) / 100
- }
- export const stepCanvasScale = (scale: number, direction: CanvasScaleDirection) =>
- normalizeCanvasScale(scale + (direction === 'in' ? CANVAS_SCALE_STEP : -CANVAS_SCALE_STEP))
- export const calculateFitCanvas = ({
- viewportWidth,
- viewportHeight,
- canvasWidth,
- canvasHeight,
- padding
- }: FitCanvasOptions) => {
- const safePadding = {
- top: Math.max(0, padding?.top ?? 24),
- right: Math.max(0, padding?.right ?? 24),
- bottom: Math.max(0, padding?.bottom ?? 72),
- left: Math.max(0, padding?.left ?? 24)
- }
- const availableWidth = Math.max(1, viewportWidth - safePadding.left - safePadding.right)
- const availableHeight = Math.max(1, viewportHeight - safePadding.top - safePadding.bottom)
- const safeCanvasWidth = Math.max(1, canvasWidth)
- const safeCanvasHeight = Math.max(1, canvasHeight)
- const scale = normalizeCanvasScale(
- Math.min(availableWidth / safeCanvasWidth, availableHeight / safeCanvasHeight)
- )
- return {
- scale,
- transformOrigin: { x: 0, y: 0 },
- dragOffset: {
- x: Math.round(safePadding.left + (availableWidth - safeCanvasWidth * scale) / 2),
- y: Math.round(safePadding.top + (availableHeight - safeCanvasHeight * scale) / 2)
- }
- }
- }
|