zoom.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. export function getZoomOrigin(canvas: HTMLCanvasElement | null) {
  2. if (canvas === null) {
  3. return { x: 0, y: 0 };
  4. }
  5. const context = canvas.getContext("2d");
  6. if (context === null) {
  7. return { x: 0, y: 0 };
  8. }
  9. const normalizedCanvasWidth = canvas.width / context.getTransform().a;
  10. const normalizedCanvasHeight = canvas.height / context.getTransform().d;
  11. return {
  12. x: normalizedCanvasWidth / 2,
  13. y: normalizedCanvasHeight / 2,
  14. };
  15. }
  16. export function getZoomTranslation(canvas: HTMLCanvasElement, zoom: number) {
  17. const diffMiddleOfTheCanvas = {
  18. x: (canvas.width / 2) * (zoom - 1),
  19. y: (canvas.height / 2) * (zoom - 1),
  20. };
  21. // Due to JavaScript float precision, we fix to fix decimals count to have symmetric zoom
  22. return {
  23. x: parseFloat(diffMiddleOfTheCanvas.x.toFixed(8)),
  24. y: parseFloat(diffMiddleOfTheCanvas.y.toFixed(8)),
  25. };
  26. }
  27. export function getNormalizedZoom(zoom: number): number {
  28. const normalizedZoom = parseFloat(zoom.toFixed(2));
  29. const clampedZoom = Math.max(0.1, Math.min(normalizedZoom, 2));
  30. return clampedZoom;
  31. }