Viewport
Viewport encapsulates camera position, zoom level, canvas dimensions, and all coordinate-space conversions between canvas pixels and texture pixels.
Types
new Viewport(options: ViewportOptions)
export interface ViewportOptions {
/**
* Size of the texture to display in the viewport.
* This is used to calculate the camera bounds and the zoom level.
*/
textureSize: Vec2;
/**
* Default zoom level.
* Can be overridden by passing a texture with a different size than the default one.
* @default 4
*/
zoom?: number;
/**
* Minimum zoom level. Must be under the max zoom level.
* @default 1
*/
zoomMin?: number;
/**
* Maximum zoom level. Must be above the min zoom level.
* @default 32
*/
zoomMax?: number;
/**
* Sensitivity of zooming when using the mouse wheel. The higher, the faster the zoom changes.
* If the zoom level is under 1, the sensitivity is divided by 10 to allow finer control.
* @default 0.1
*/
zoomSensitivity?: number;
}Methods
resizeCanvas
resizeCanvas(width: number, height: number): voidUpdates the canvas size while preserving the current camera position. Shifts the camera by half the size delta so the same world point stays at the center of the screen.
applyZoom
applyZoom(delta: number, originX: number, originY: number): voidAdjusts the zoom level by delta (wheel units × sensitivity), keeping the point at (originX, originY) in canvas space fixed on screen.
applyPan
applyPan(dx: number, dy: number): voidTranslates the camera by (dx, dy) pixels in canvas space.
setCanvasSize
setCanvasSize(width: number, height: number): voidUpdates the tracked canvas dimensions. Call this whenever the visible canvas is resized.
setTextureSize
setTextureSize(size: number): voidUpdates the tracked texture size used in UV and screen-rect computations.
center
center(): voidResets the camera so the texture is centered in the current canvas.
getMouseCanvasPosition
getMouseCanvasPosition(mx: number, my: number): Vec2Converts a raw mouse event position (relative to the page) to canvas-local coordinates by subtracting the canvas bounding-rect offset.
getMouseTexturePosition
getMouseTexturePosition(
mx: number,
my: number,
opts: { bounds: DOMRect; limit?: boolean }
): Vec2Converts a mouse position to texture-space pixel coordinates at the current zoom and camera offset.
bounds— the canvasDOMRectobtained fromcanvas.getBoundingClientRect()limit— whentrue, clamps the result to[0, textureSize - 1]
Example
canvas.addEventListener("mousemove", (e) => {
const bounds = canvas.getBoundingClientRect();
const pos = viewport.getMouseTexturePosition(e.clientX, e.clientY, { bounds, limit: true });
console.log(pos.x, pos.y); // texture-space coordinates
});getTextureScreenRect
getTextureScreenRect(): { x: number; y: number; width: number; height: number }Returns the screen-space rectangle occupied by the texture at the current zoom and camera position. Useful for rendering the checkerboard background clip region or positioning DOM overlays.