diff --git a/src/components/canvas/canvas-gestures.ts b/src/components/canvas/canvas-gestures.ts
new file mode 100644
index 00000000..ae303f55
--- /dev/null
+++ b/src/components/canvas/canvas-gestures.ts
@@ -0,0 +1,25 @@
+export interface Point {
+ x: number;
+ y: number;
+}
+
+/** Where the edit sits in the canvas and how large it is drawn. */
+export interface View {
+ x: number;
+ y: number;
+ zoom: number;
+}
+
+export interface ZoomLimits {
+ min: number;
+ max: number;
+}
+
+const clamp = (value: number, { min, max }: ZoomLimits): number => Math.min(Math.max(value, min), max);
+
+/** Zooms to `zoom`, within the limits, so the point under `anchor` stays under it. */
+export function zoomAbout(view: View, anchor: Point, zoom: number, limits: ZoomLimits): View {
+ const next = clamp(zoom, limits);
+ const ratio = next / view.zoom;
+ return { zoom: next, x: anchor.x - (anchor.x - view.x) * ratio, y: anchor.y - (anchor.y - view.y) * ratio };
+}
diff --git a/src/components/canvas/shotstack-canvas.ts b/src/components/canvas/shotstack-canvas.ts
index 2b5a0465..d8d5c1f7 100644
--- a/src/components/canvas/shotstack-canvas.ts
+++ b/src/components/canvas/shotstack-canvas.ts
@@ -1,4 +1,5 @@
import { BufferingNotice, visibleBounds } from "@canvas/buffering-notice";
+import { zoomAbout, type View } from "@canvas/canvas-gestures";
import type { Player } from "@canvas/players/player";
import { AlignmentGuides } from "@canvas/system/alignment-guides";
import { createWebGLErrorOverlay } from "@canvas/webgl-error-overlay";
@@ -156,6 +157,28 @@ export class Canvas {
root.addEventListener("pointerdown", this.onPanPointerDown);
}
+ private getView(): View {
+ const { x, y } = this.viewportContainer?.position ?? { x: 0, y: 0 };
+ return { x, y, zoom: this.currentZoom };
+ }
+
+ private setView({ x, y, zoom }: View): void {
+ if (!this.viewportContainer) return;
+
+ this.currentZoom = zoom;
+ this.viewportContainer.position.set(x, y);
+ this.viewportContainer.scale.set(zoom);
+ this.syncContentTransforms();
+ }
+
+ private get viewportCentre(): { x: number; y: number } {
+ return { x: this.viewportSize.width / 2, y: this.viewportSize.height / 2 };
+ }
+
+ private get zoomLimits(): { min: number; max: number } {
+ return { min: this.minZoom, max: this.maxZoom };
+ }
+
private onWheel(e: WheelEvent): void {
// Allow native scrolling inside toolbar popups (font picker, TTS voice list, etc.).
const target = e.target as HTMLElement;
@@ -169,29 +192,11 @@ export class Canvas {
if (!this.viewportContainer) return;
if (e.ctrlKey) {
- const scaleFactor = Math.exp(-e.deltaY / 100);
- const newZoom = this.currentZoom * scaleFactor;
- const oldZoom = this.currentZoom;
- this.currentZoom = Math.min(Math.max(newZoom, this.minZoom), this.maxZoom);
-
- const stageCenter = {
- x: this.viewportSize.width / 2,
- y: this.viewportSize.height / 2
- };
-
- const distanceFromCenter = {
- x: this.viewportContainer.position.x - stageCenter.x,
- y: this.viewportContainer.position.y - stageCenter.y
- };
-
- const zoomRatio = this.currentZoom / oldZoom;
-
- this.viewportContainer.position.x = stageCenter.x + distanceFromCenter.x * zoomRatio;
- this.viewportContainer.position.y = stageCenter.y + distanceFromCenter.y * zoomRatio;
+ this.zoomBy(Math.exp(-e.deltaY / 100));
+ return;
+ }
- this.viewportContainer.scale.x = this.currentZoom;
- this.viewportContainer.scale.y = this.currentZoom;
- } else if (e.shiftKey) {
+ if (e.shiftKey) {
this.viewportContainer.position.x -= e.deltaY || e.deltaX;
} else {
this.viewportContainer.position.y -= e.deltaY;
@@ -315,6 +320,14 @@ export class Canvas {
return this.currentZoom;
}
+ /**
+ * Multiply the zoom by `factor`, within the limits, about the centre of the viewport.
+ * @internal
+ */
+ public zoomBy(factor: number): void {
+ this.setView(zoomAbout(this.getView(), this.viewportCentre, this.currentZoom * factor, this.zoomLimits));
+ }
+
/**
* The user supplied Studio root element.
* @internal
diff --git a/src/core/ui/canvas-zoom-controls.ts b/src/core/ui/canvas-zoom-controls.ts
new file mode 100644
index 00000000..e453fe3b
--- /dev/null
+++ b/src/core/ui/canvas-zoom-controls.ts
@@ -0,0 +1,48 @@
+import type { Canvas } from "@canvas/shotstack-canvas";
+
+import type { UIRegistration } from "./ui-controller";
+
+const ZOOM_STEP = 1.2;
+
+const icon = (paths: string): string =>
+ ``;
+
+const ICON_OUT = icon('');
+const ICON_FIT = icon('');
+const ICON_IN = icon('');
+
+/** Zoom buttons for the canvas. Pinching is a multipoint gesture, so touch needs a single-tap way to do the same. */
+export class CanvasZoomControls implements UIRegistration {
+ private element: HTMLDivElement | null = null;
+
+ constructor(private readonly canvas: Canvas) {}
+
+ mount(container: HTMLElement): void {
+ const element = document.createElement("div");
+ element.className = "ss-canvas-zoom";
+ element.setAttribute("role", "group");
+ element.setAttribute("aria-label", "Canvas zoom");
+ element.append(
+ this.button("out", "Zoom out", ICON_OUT, () => this.canvas.zoomBy(1 / ZOOM_STEP)),
+ this.button("fit", "Fit to screen", ICON_FIT, () => this.canvas.zoomToFit()),
+ this.button("in", "Zoom in", ICON_IN, () => this.canvas.zoomBy(ZOOM_STEP))
+ );
+ container.append(element);
+ this.element = element;
+ }
+
+ dispose(): void {
+ this.element?.remove();
+ this.element = null;
+ }
+
+ private button(name: string, label: string, svg: string, onClick: () => void): HTMLButtonElement {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = `ss-canvas-zoom-btn ss-canvas-zoom-${name}`;
+ button.setAttribute("aria-label", label);
+ button.innerHTML = svg;
+ button.addEventListener("click", onClick);
+ return button;
+ }
+}
diff --git a/src/core/ui/ui-controller.ts b/src/core/ui/ui-controller.ts
index e88ba761..81a9784b 100644
--- a/src/core/ui/ui-controller.ts
+++ b/src/core/ui/ui-controller.ts
@@ -8,6 +8,7 @@ import type * as pixi from "pixi.js";
import { AssetToolbar } from "./asset-toolbar";
import { CanvasToolbar } from "./canvas-toolbar";
+import { CanvasZoomControls } from "./canvas-zoom-controls";
import { ClipToolbar } from "./clip-toolbar";
import { GenerateToolbar } from "./generate-toolbar";
import { MediaToolbar } from "./media-toolbar";
@@ -177,7 +178,7 @@ export class UIController {
const ui = new UIController(edit, canvas, options);
ui.subscribeToEvents();
canvas.setUIController(ui);
- ui.registerStandardToolbars();
+ ui.registerStandardToolbars(canvas);
// Auto-mount if canvas is already loaded (element exists in DOM)
// This handles the case where UIController is created after canvas.load()
@@ -238,7 +239,7 @@ export class UIController {
/**
* Register all standard toolbars. Called by create() factory.
*/
- private registerStandardToolbars(): void {
+ private registerStandardToolbars(canvas: Canvas): void {
// Selection handles
if (this.selectionHandlesEnabled) {
this.registerCanvasOverlay(new SelectionHandles(this.edit));
@@ -263,6 +264,7 @@ export class UIController {
maxPixels: this.maxPixels
});
this.registerUtility(this.canvasToolbar);
+ this.registerUtility(new CanvasZoomControls(canvas));
// Wire up toolbar callbacks to Edit methods
this.canvasToolbar.onResolutionChange((w, h) => this.edit.setOutputSize(w, h));
diff --git a/src/styles/index.css b/src/styles/index.css
index fd6e7057..bf3f03c4 100644
--- a/src/styles/index.css
+++ b/src/styles/index.css
@@ -18,6 +18,7 @@
@import "./ui/text-to-speech-toolbar.css";
@import "./ui/clip-toolbar.css";
@import "./ui/canvas-toolbar.css";
+@import "./ui/canvas-zoom.css";
@import "./ui/asset-toolbar.css";
@import "./ui/font-color-picker.css";
@import "./ui/background-color-picker.css";
diff --git a/src/styles/ui/canvas-zoom.css b/src/styles/ui/canvas-zoom.css
new file mode 100644
index 00000000..09f12e7f
--- /dev/null
+++ b/src/styles/ui/canvas-zoom.css
@@ -0,0 +1,47 @@
+.ss-canvas-zoom {
+ display: none;
+}
+
+/* Pinching is no use to anyone who can't use two fingers, so touch gets buttons too. A mouse has the wheel. */
+@media (pointer: coarse) {
+ .ss-canvas-zoom {
+ position: absolute;
+ right: 24px;
+ bottom: 24px;
+ z-index: 9;
+ display: flex;
+ gap: 2px;
+ padding: 6px;
+ background: rgba(255, 255, 255, 0.98);
+ border: 1px solid rgba(0, 0, 0, 0.06);
+ border-radius: 14px;
+ box-shadow:
+ 0 2px 8px rgba(0, 0, 0, 0.06),
+ 0 8px 24px rgba(0, 0, 0, 0.08);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ }
+
+ .ss-canvas-zoom-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 44px;
+ height: 44px;
+ padding: 0;
+ background: transparent;
+ border: none;
+ border-radius: 8px;
+ color: rgba(0, 0, 0, 0.65);
+ cursor: pointer;
+ }
+
+ .ss-canvas-zoom-btn:active {
+ background: rgba(0, 0, 0, 0.1);
+ }
+
+ .ss-canvas-zoom-btn svg {
+ width: 20px;
+ height: 20px;
+ }
+}
diff --git a/test-package.js b/test-package.js
index 2fc2fb1d..c918fbce 100644
--- a/test-package.js
+++ b/test-package.js
@@ -45,7 +45,8 @@ const CONTRACT = {
"getViewportContainer(",
"updateViewportForSize(",
"pauseTicker(",
- "resumeTicker("
+ "resumeTicker(",
+ "zoomBy("
],
Timeline: [
"draw(): void;",
diff --git a/tests/canvas-gestures.test.ts b/tests/canvas-gestures.test.ts
new file mode 100644
index 00000000..0fd7e553
--- /dev/null
+++ b/tests/canvas-gestures.test.ts
@@ -0,0 +1,33 @@
+/**
+ * @jest-environment jsdom
+ */
+
+import { zoomAbout, type Point, type View } from "@canvas/canvas-gestures";
+
+const LIMITS = { min: 0.1, max: 4 };
+
+/** The point of the edit that sits under a screen point. */
+const worldAt = (view: View, screen: Point): Point => ({ x: (screen.x - view.x) / view.zoom, y: (screen.y - view.y) / view.zoom });
+
+describe("zoomAbout", () => {
+ it("keeps the point under the anchor still", () => {
+ const view = { x: 40, y: -20, zoom: 1.5 };
+ const anchor = { x: 300, y: 200 };
+
+ const zoomed = zoomAbout(view, anchor, 3, LIMITS);
+
+ expect(zoomed.zoom).toBe(3);
+ expect(worldAt(zoomed, anchor)).toEqual(worldAt(view, anchor));
+ });
+
+ it("clamps to the limits and anchors on the zoom it reached", () => {
+ const view = { x: 10, y: 10, zoom: 3 };
+ const anchor = { x: 120, y: 80 };
+
+ const zoomed = zoomAbout(view, anchor, 12, LIMITS);
+
+ expect(zoomed.zoom).toBe(4);
+ expect(worldAt(zoomed, anchor).x).toBeCloseTo(worldAt(view, anchor).x);
+ expect(zoomAbout(view, anchor, 0.001, LIMITS).zoom).toBe(0.1);
+ });
+});
diff --git a/tests/canvas-zoom-controls.test.ts b/tests/canvas-zoom-controls.test.ts
new file mode 100644
index 00000000..0ed7451f
--- /dev/null
+++ b/tests/canvas-zoom-controls.test.ts
@@ -0,0 +1,84 @@
+/**
+ * @jest-environment jsdom
+ */
+
+import type { Canvas } from "@canvas/shotstack-canvas";
+import { CanvasZoomControls } from "@core/ui/canvas-zoom-controls";
+
+// @ts-expect-error - Jest transforms this via moduleNameMapper to css-inline.js mock
+import styles from "../src/styles/index.css?inline";
+
+describe("CanvasZoomControls", () => {
+ let host: HTMLElement;
+ let canvas: { zoomBy: jest.Mock; zoomToFit: jest.Mock };
+ let controls: CanvasZoomControls;
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ host = document.createElement("div");
+ document.body.append(host);
+ canvas = { zoomBy: jest.fn(), zoomToFit: jest.fn() };
+ controls = new CanvasZoomControls(canvas as unknown as Canvas);
+ controls.mount(host);
+ });
+
+ afterEach(() => controls.dispose());
+
+ const button = (name: string): HTMLButtonElement => host.querySelector(`.ss-canvas-zoom-${name}`) as HTMLButtonElement;
+
+ it("mounts three real buttons with labels and stable class names", () => {
+ const labelled = ["out", "fit", "in"].map(name => [button(name).tagName, button(name).type, button(name).getAttribute("aria-label")]);
+
+ expect(labelled).toEqual([
+ ["BUTTON", "button", "Zoom out"],
+ ["BUTTON", "button", "Fit to screen"],
+ ["BUTTON", "button", "Zoom in"]
+ ]);
+ });
+
+ it("zooms out by a fifth", () => {
+ button("out").click();
+
+ expect(canvas.zoomBy).toHaveBeenCalledWith(1 / 1.2);
+ expect(canvas.zoomToFit).not.toHaveBeenCalled();
+ });
+
+ it("zooms in by a fifth", () => {
+ button("in").click();
+
+ expect(canvas.zoomBy).toHaveBeenCalledWith(1.2);
+ expect(canvas.zoomToFit).not.toHaveBeenCalled();
+ });
+
+ it("fits the edit to the canvas", () => {
+ button("fit").click();
+
+ expect(canvas.zoomToFit).toHaveBeenCalledTimes(1);
+ expect(canvas.zoomBy).not.toHaveBeenCalled();
+ });
+
+ it("removes itself when disposed", () => {
+ controls.dispose();
+
+ expect(host.querySelector(".ss-canvas-zoom")).toBeNull();
+ });
+});
+
+describe("canvas zoom buttons CSS", () => {
+ const coarse: string[] = styles.match(/@media \(pointer: coarse\) \{[\s\S]*?\n\}/g) ?? [];
+ const outside = coarse.reduce((css, block) => css.replace(block, ""), styles as string);
+
+ it("hides the buttons everywhere but under a coarse primary pointer", () => {
+ const bodies = [...outside.matchAll(/[^{}]*ss-canvas-zoom[^{}]*\{([^}]*)\}/g)].map(([, body]) => body.trim());
+
+ expect(bodies).toEqual(["display: none;"]);
+ expect(coarse.join("\n")).toMatch(/\.ss-canvas-zoom \{[^}]*display: flex;/);
+ });
+
+ it("gives each button a target of at least 44px", () => {
+ const [, width, height] = coarse.join("\n").match(/\.ss-canvas-zoom-btn \{[^}]*width: (\d+)px;[^}]*height: (\d+)px;/) ?? [];
+
+ expect(Number(width)).toBeGreaterThanOrEqual(44);
+ expect(Number(height)).toBeGreaterThanOrEqual(44);
+ });
+});
diff --git a/tests/canvas-zoom.test.ts b/tests/canvas-zoom.test.ts
new file mode 100644
index 00000000..e440c83f
--- /dev/null
+++ b/tests/canvas-zoom.test.ts
@@ -0,0 +1,157 @@
+/**
+ * @jest-environment jsdom
+ */
+
+import { Canvas } from "@canvas/shotstack-canvas";
+
+// pixi.js ships untransformed ESM that jest can't parse; zooming never touches a renderer.
+jest.mock("pixi.js", () => ({
+ Application: jest.fn(),
+ Container: jest.fn(),
+ Graphics: jest.fn(),
+ Rectangle: jest.fn()
+}));
+jest.mock("pixi.js/app", () => ({}));
+jest.mock("pixi.js/events", () => ({}));
+jest.mock("pixi.js/graphics", () => ({}));
+jest.mock("pixi.js/text", () => ({}));
+jest.mock("pixi.js/text-html", () => ({}));
+jest.mock("pixi.js/sprite-tiling", () => ({}));
+jest.mock("pixi.js/filters", () => ({}));
+jest.mock("pixi.js/mesh", () => ({}));
+
+const VIEWPORT = { width: 800, height: 600 };
+const LIMITS = { min: 0.1, max: 4 };
+
+interface State {
+ zoom: number;
+ x: number;
+ y: number;
+}
+
+/** The Ctrl+wheel zoom as it was written before the shared helper, kept here as the oracle. */
+function legacyCtrlWheel(start: State, deltaY: number): State {
+ const scaleFactor = Math.exp(-deltaY / 100);
+ const newZoom = start.zoom * scaleFactor;
+ const oldZoom = start.zoom;
+ const zoom = Math.min(Math.max(newZoom, LIMITS.min), LIMITS.max);
+
+ const stageCenter = { x: VIEWPORT.width / 2, y: VIEWPORT.height / 2 };
+ const distanceFromCenter = { x: start.x - stageCenter.x, y: start.y - stageCenter.y };
+ const zoomRatio = zoom / oldZoom;
+
+ return { zoom, x: stageCenter.x + distanceFromCenter.x * zoomRatio, y: stageCenter.y + distanceFromCenter.y * zoomRatio };
+}
+
+function canvasAt({ zoom, x, y }: State) {
+ const point = (px: number, py: number) => ({
+ x: px,
+ y: py,
+ set(nx: number, ny: number = nx) {
+ this.x = nx;
+ this.y = ny;
+ }
+ });
+ const viewportContainer = { position: point(x, y), scale: point(zoom, zoom) };
+ const overlayContainer = { position: point(0, 0), scale: point(1, 1) };
+ const canvas = Object.create(Canvas.prototype) as Canvas;
+ Object.assign(canvas, { viewportContainer, overlayContainer, currentZoom: zoom, viewportSize: VIEWPORT, minZoom: LIMITS.min, maxZoom: LIMITS.max });
+ return {
+ canvas,
+ viewportContainer,
+ overlayContainer,
+ read: (): State => ({ zoom: canvas.getZoom(), x: viewportContainer.position.x, y: viewportContainer.position.y })
+ };
+}
+
+function wheel(canvas: Canvas, init: { deltaY: number; deltaX?: number; ctrlKey?: boolean; shiftKey?: boolean }): { preventDefault: jest.Mock } {
+ const event = {
+ target: document.createElement("div"),
+ deltaX: 0,
+ ctrlKey: false,
+ shiftKey: false,
+ preventDefault: jest.fn(),
+ stopPropagation: jest.fn(),
+ ...init
+ };
+ (canvas as unknown as { onWheel(e: unknown): void }).onWheel(event);
+ return event;
+}
+
+describe("Ctrl+wheel zoom", () => {
+ const starts: State[] = [
+ { zoom: 1, x: 100, y: 50 },
+ { zoom: 0.5, x: -250, y: 310.5 },
+ { zoom: 2.25, x: 640.25, y: -80.125 },
+ { zoom: 3.9, x: 12, y: 700 },
+ { zoom: 0.11, x: 400, y: 300 }
+ ];
+ // Gentle, strong and extreme ticks in both directions, so some runs hit each limit.
+ const deltas = [-400, -120, -17.5, 0, 3, 40, 120, 400];
+
+ it.each(starts.flatMap(start => deltas.map(deltaY => [start, deltaY] as const)))(
+ "matches the previous maths from %j with deltaY %d",
+ (start, deltaY) => {
+ const { canvas, read } = canvasAt(start);
+
+ wheel(canvas, { deltaY, ctrlKey: true });
+
+ expect(read()).toEqual(legacyCtrlWheel(start, deltaY));
+ }
+ );
+
+ it("keeps the overlay container in step with the viewport container", () => {
+ const { canvas, viewportContainer, overlayContainer } = canvasAt({ zoom: 1, x: 100, y: 50 });
+
+ wheel(canvas, { deltaY: -120, ctrlKey: true });
+
+ expect(overlayContainer.scale.x).toBe(viewportContainer.scale.x);
+ expect(overlayContainer.position.x).toBe(viewportContainer.position.x);
+ expect(overlayContainer.position.y).toBe(viewportContainer.position.y);
+ });
+
+ it("still pans, rather than zooms, without Ctrl", () => {
+ const { canvas, read } = canvasAt({ zoom: 1.5, x: 100, y: 50 });
+
+ const event = wheel(canvas, { deltaX: 10, deltaY: 30 });
+
+ expect(read()).toEqual({ zoom: 1.5, x: 90, y: 20 });
+ expect(event.preventDefault).toHaveBeenCalled();
+ });
+});
+
+describe("Canvas.zoomBy", () => {
+ const worldAtCentre = ({ zoom, x, y }: State) => ({ x: (VIEWPORT.width / 2 - x) / zoom, y: (VIEWPORT.height / 2 - y) / zoom });
+
+ it("keeps the centre of the viewport fixed", () => {
+ const start = { zoom: 1.5, x: 120, y: -40 };
+ const { canvas, read } = canvasAt(start);
+
+ canvas.zoomBy(1.2);
+
+ expect(read().zoom).toBeCloseTo(1.8);
+ expect(worldAtCentre(read()).x).toBeCloseTo(worldAtCentre(start).x);
+ expect(worldAtCentre(read()).y).toBeCloseTo(worldAtCentre(start).y);
+ });
+
+ it("agrees with a Ctrl+wheel tick of the same factor", () => {
+ const start = { zoom: 1, x: 100, y: 50 };
+ const byWheel = canvasAt(start);
+ const byButton = canvasAt(start);
+
+ wheel(byWheel.canvas, { deltaY: -50, ctrlKey: true });
+ byButton.canvas.zoomBy(Math.exp(0.5));
+
+ expect(byButton.read()).toEqual(byWheel.read());
+ });
+
+ it("stops at the limits", () => {
+ const { canvas } = canvasAt({ zoom: 3.8, x: 0, y: 0 });
+
+ canvas.zoomBy(1.2);
+ expect(canvas.getZoom()).toBe(4);
+
+ canvas.zoomBy(0.0001);
+ expect(canvas.getZoom()).toBe(0.1);
+ });
+});