Skip to content

Is it possible to zoom in / out depending on the current center of the image? #30

@adriandotdev

Description

@adriandotdev

I notice that when i move around on the editor and press zoom in / out, it goes back to the main center of the image.

Is it possible to zoom in/out depending on the current center of the image?

here's my code

 // Get the center of the currently visible viewport
  const getCurrentContentCenter = () => {
    if (!editor.current || !editorContainer.current) return { x: 0, y: 0 };
    const container = editorContainer.current;
    const zoom = editor.current.zoomLevel;

    const centerX = container.scrollLeft + container.clientWidth / 2;
    const centerY = container.scrollTop + container.clientHeight / 2;

    // Convert to content coordinates
    return {
      x: centerX / zoom,
      y: centerY / zoom,
    };
  };

  // Zoom while keeping the current view center fixed
  const zoomAroundContentCenter = (factor: number) => {
    if (!editor.current || !editorContainer.current) return;

    const container = editorContainer.current;
    const oldZoom = editor.current.zoomLevel;
    const center = getCurrentContentCenter();

    const newZoom = Math.max(0.2, oldZoom * factor);
    editor.current.zoomLevel = newZoom;
    setZoomLevel(newZoom);

    // Adjust scroll so the same content center stays in the viewport
    container.scrollLeft = center.x * newZoom - container.clientWidth / 2;
    container.scrollTop = center.y * newZoom - container.clientHeight / 2;

    // Update markers so stroke/font scales correctly
    updateStrokeWidthsOnZoom();
  };

  // Toolbar zoom buttons
  const zoomIn = () => zoomAroundContentCenter(1.1);
  const zoomOut = () => zoomAroundContentCenter(0.9);


  const updateStrokeWidthsOnZoom = () => {
    const zoom = editor.current?.zoomLevel ?? 1;

    markerEditors.current.forEach(editor => {
      const marker = editor.marker as BoundingBoxMarker;
      marker.strokeWidth = BASE_STROKE_WIDTH / zoom;
      marker.fontSize = {
        step: 1,
        units: "px",
        value: BASE_FONT_SIZE / zoom,
      };
      marker.adjustVisual();
    });
  };

Looking forwrad on your response.

Thanks, guys.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions