zooming and panning

This commit is contained in:
Evert Prants 2023-01-18 20:11:54 +02:00
parent 668b2c5001
commit b82f1b03f2
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
6 changed files with 183 additions and 56 deletions

View File

@ -1,6 +1,17 @@
<template>
<div class="relative h-full w-full bg-white">
<canvas ref="canvas" class="border-none" />
<div class="relative h-full w-full overflow-hidden bg-gray-100">
<canvas
ref="canvas"
class="border-none bg-white"
:style="{
width: `${canvasDim[0] * canvasZoom}px`,
height: `${canvasDim[1] * canvasZoom}px`,
transformOrigin: 'top left',
transform: `translate(${canvasPos[0]}px, ${canvasPos[1]}px)`,
}"
/>
</div>
<PlannerToolbar>
<PlannerTool
v-for="toolItem of toolbar"
@ -54,7 +65,12 @@ import { useSessionStorage } from '@vueuse/core';
import type { Component } from 'vue';
import { onMounted, ref, shallowRef } from 'vue';
import { HousePlanner } from '../../modules/house-planner';
import { Layer, ToolEvent } from '../../modules/house-planner/interfaces';
import {
Layer,
RepositionEvent,
ToolEvent,
Vec2,
} from '../../modules/house-planner/interfaces';
import { LayerObjectType } from '../../modules/house-planner/types';
import deepUnref from '../../utils/deep-unref';
import { ToolbarTool } from './interfaces/toolbar.interfaces';
@ -69,6 +85,9 @@ const canvas = ref();
const module = shallowRef(new HousePlanner());
const tool = ref<string | undefined>('move');
const subTool = ref<string | undefined>(undefined);
const canvasDim = ref<Vec2>([1920, 1080]);
const canvasPos = ref<Vec2>([0, 0]);
const canvasZoom = ref<number>(1);
const serializedLayers = useSessionStorage<Layer[]>(
'roomData',
[
@ -167,7 +186,10 @@ const updateObjectProperty = (
onMounted(() => {
const cleanUp = module.value.initialize(
canvas.value,
deepUnref(serializedLayers.value)
deepUnref(serializedLayers.value),
[1920, 1080],
canvasPos,
canvasZoom.value
);
const events: Record<string, (e: CustomEvent) => void> = {
@ -181,6 +203,10 @@ onMounted(() => {
tool.value = e.detail.primary;
subTool.value = e.detail.secondary as string;
},
'hpc:position': (e: CustomEvent<RepositionEvent>) => {
//canvasPos.value = e.detail.position;
canvasZoom.value = e.detail.zoom;
},
};
Object.keys(events).forEach((event) =>

View File

@ -1,3 +1,4 @@
import type { Ref } from 'vue';
import { HousePlannerCanvasGrid } from './grid';
import {
BezierSegment,
@ -5,6 +6,7 @@ import {
LayerObject,
Line,
LineSegment,
RepositionEvent,
Vec2,
} from './interfaces';
import { HousePlannerCanvasTools } from './tools';
@ -12,9 +14,12 @@ import {
rad2deg,
vec2Add,
vec2AngleFromOrigin,
vec2Clamp,
vec2Distance,
vec2DivideScalar,
vec2MultiplyScalar,
vec2PointFromAngle,
vec2Sub,
} from './utils';
export class HousePlannerCanvas {
@ -23,9 +28,15 @@ export class HousePlannerCanvas {
public tools = new HousePlannerCanvasTools(this);
public grid = new HousePlannerCanvasGrid(this, 8);
constructor(public canvas: HTMLCanvasElement) {
constructor(
public canvas: HTMLCanvasElement,
public canvasDim: Vec2,
public canvasPos: Ref<Vec2>,
public canvasZoom = 1
) {
this.ctx = this.canvas.getContext('2d')!;
this.setupEvents();
this.resizeCanvas();
}
get width() {
@ -41,6 +52,13 @@ export class HousePlannerCanvas {
this.draw();
}
resizeCanvas() {
const [w, h] = this.canvasDim;
this.canvas.width = w;
this.canvas.height = h;
this.draw();
}
cleanUp() {
this.tools.cleanUp();
window.removeEventListener('keyup', this.boundKeyUpEvent);
@ -206,6 +224,17 @@ export class HousePlannerCanvas {
return layer;
}
translateCanvas(offset: Vec2) {
const realSize = vec2MultiplyScalar(this.canvasDim, this.canvasZoom);
this.canvasPos.value = vec2Sub(this.canvasPos.value, offset);
this.repositionEvent();
}
zoomCanvas(diff: number) {
this.canvasZoom -= diff;
this.repositionEvent();
}
private keyDownEvent(e: KeyboardEvent) {
if (e.target !== document.body && e.target != null) return;
e.preventDefault();
@ -287,4 +316,15 @@ export class HousePlannerCanvas {
}
}
}
private repositionEvent() {
this.canvas.dispatchEvent(
new CustomEvent<RepositionEvent>('hpc:position', {
detail: {
position: this.canvasPos.value,
zoom: this.canvasZoom,
},
})
);
}
}

View File

@ -1,15 +1,26 @@
import { Ref } from 'vue';
import { HousePlannerCanvas } from './canvas';
import { Layer } from './interfaces';
import { Layer, Vec2 } from './interfaces';
export class HousePlanner {
public canvas!: HTMLCanvasElement;
public manager?: HousePlannerCanvas;
initialize(canvas: HTMLCanvasElement, initialData: Layer[]) {
initialize(
canvas: HTMLCanvasElement,
initialData: Layer[],
canvasDim: Vec2,
canvasPos: Ref<Vec2>,
canvasZoom = 1,
editable = true
) {
this.canvas = canvas;
this.resizeCanvas();
this.addResizeEvents();
this.manager = new HousePlannerCanvas(canvas);
this.manager = new HousePlannerCanvas(
canvas,
canvasDim,
canvasPos,
canvasZoom
);
this.manager.layers = initialData;
this.manager.tools.selectLayer(
initialData[initialData.findIndex((layer) => layer.active)]
@ -21,19 +32,6 @@ export class HousePlanner {
}
cleanUp() {
window.removeEventListener('resize', this.boundResizeEvent);
this.manager?.cleanUp();
}
private addResizeEvents() {
window.addEventListener('resize', this.boundResizeEvent);
}
resizeCanvas() {
this.canvas.width = this.canvas.parentElement!.clientWidth;
this.canvas.height = this.canvas.parentElement!.clientHeight;
this.manager?.draw();
}
private boundResizeEvent = this.resizeCanvas.bind(this);
}

View File

@ -55,6 +55,11 @@ export interface ToolEvent {
secondary?: unknown;
}
export interface RepositionEvent {
position: Vec2;
zoom: number;
}
export interface ICanvasToolBase<U = undefined> {
name: string;
subTool: U | undefined;

View File

@ -1,3 +1,4 @@
import { clamp } from '@vueuse/core';
import type { HousePlannerCanvas } from './canvas';
import { HousePlannerCanvasHistory } from './history';
import {
@ -6,12 +7,20 @@ import {
Layer,
LayerObject,
Line,
RepositionEvent,
ToolEvent,
Vec2,
} from './interfaces';
import { LineTool } from './tools/line';
import { MoveTool } from './tools/move';
import { vec2Distance, vec2Snap, vec2Sub } from './utils';
import {
vec2Add,
vec2Distance,
vec2DivideScalar,
vec2MultiplyScalar,
vec2Snap,
vec2Sub,
} from './utils';
export class HousePlannerCanvasTools {
public selectedLayer?: Layer;
@ -237,12 +246,7 @@ export class HousePlannerCanvasTools {
this.dragEvent(e.clientX, e.clientY);
}
onMouseDown(e: MouseEvent) {
this.mousePosition = [e.clientX, e.clientY];
this.mouseClickPosition = [...this.mousePosition];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
this.dragging = true;
this.mouseClickPosition = [e.clientX, e.clientY];
this.moved = false;
this.pointerDown();
@ -282,11 +286,6 @@ export class HousePlannerCanvasTools {
onTouchStart(e: TouchEvent) {
e.preventDefault();
const touch = e.touches[0] || e.changedTouches[0];
this.mousePosition = [touch.pageX, touch.pageY];
this.mouseClickPosition = [...this.mousePosition];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
this.dragging = true;
this.moved = false;
@ -309,18 +308,43 @@ export class HousePlannerCanvasTools {
onMouseWheel(e: WheelEvent) {
// TODO: zoom
// ev.preventDefault();
// this._mousex = ev.clientX;
// this._mousey = ev.clientY;
// const scaleX = (ev.clientX - this._posx) / this._zoom;
// const scaleY = (ev.clientY - this._posy) / this._zoom;
// ev.deltaY < 0 ? (this._zoom *= 1.2) : (this._zoom /= 1.2);
// this._zoom = clamp(this._zoom, this._minZoom, this._maxZoom);
// this._posx = ev.clientX - scaleX * this._zoom;
// this._posy = ev.clientY - scaleY * this._zoom;
// const realSize = this._zoom * this._size;
// this._posx = clamp(this._posx, this._cursorx - realSize, this._cursorx);
// this._posy = clamp(this._posy, this._cursory - realSize, this._cursory);
e.preventDefault();
this.realMousePos(e.clientX, e.clientY);
const scaleX =
(e.clientX - this.manager.canvasPos.value[0]) / this.manager.canvasZoom;
const scaleY =
(e.clientY - this.manager.canvasPos.value[1]) / this.manager.canvasZoom;
e.deltaY < 0
? (this.manager.canvasZoom *= 1.2)
: (this.manager.canvasZoom /= 1.2);
this.manager.canvasZoom = clamp(this.manager.canvasZoom, 0.1, 10);
this.manager.canvasPos.value = [
e.clientX - scaleX * this.manager.canvasZoom,
e.clientY - scaleY * this.manager.canvasZoom,
];
this.manager.canvasPos.value = [
clamp(
this.manager.canvasPos.value[0],
this.mousePosition[0] - this.manager.canvasDim[0],
this.mousePosition[0]
),
clamp(
this.manager.canvasPos.value[1],
this.mousePosition[1] - this.manager.canvasDim[1],
this.mousePosition[1]
),
];
this.canvas.dispatchEvent(
new CustomEvent<RepositionEvent>('hpc:position', {
detail: {
position: this.manager.canvasPos.value,
zoom: this.manager.canvasZoom,
},
})
);
}
onPointerLeave() {
this.dragging = false;
@ -419,6 +443,9 @@ export class HousePlannerCanvasTools {
private pointerDown() {
this.clickedOn = this.getMousedObject();
this.tool?.mouseDown(this.clickedOn || undefined);
if (!this.clickedOn) {
this.dragging = true;
}
}
private pointerUp() {
@ -432,29 +459,38 @@ export class HousePlannerCanvasTools {
this.tool?.mouseUp(this.moved);
this.dragging = false;
this.clickedOn = null;
}
private dragEvent(x: number, y: number) {
this.moved = true;
const currentPos = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
const currentPosAbsolute: Vec2 = [...this.mousePosition];
const currentPosSnapped: Vec2 = [
...(this.gridSnap ? this.mousePositionSnapped : this.mousePosition),
];
const rect = this.manager.canvas.getBoundingClientRect();
this.mousePosition = [x - rect.left, y - rect.top];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
let offset = vec2Sub(currentPos, this.mousePositionSnapped);
this.realMousePos(x, y);
let offset = vec2Sub(currentPosSnapped, this.mousePositionSnapped);
let offsetAbsolute = vec2Sub(currentPosAbsolute, this.mousePosition);
this.tool?.mouseMoved(
this.mousePositionSnapped,
offset,
this.mousePosition
);
if (this.dragging) {
const divided = vec2MultiplyScalar(
offsetAbsolute,
this.manager.canvasZoom
);
this.manager.translateCanvas(divided);
// Bias the offset
const [nx, ny] = vec2Add([x, y], divided);
this.realMousePos(nx, ny);
}
}
private selectedEvent() {
@ -464,4 +500,14 @@ export class HousePlannerCanvasTools {
})
);
}
private realMousePos(x: number, y: number) {
const rect = this.manager.canvas.getBoundingClientRect();
const scaleX = this.canvas.width / rect.width;
const scaleY = this.canvas.height / rect.height;
this.mousePosition = [(x - rect.left) * scaleX, (y - rect.top) * scaleY];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
}
}

View File

@ -1,3 +1,4 @@
import { clamp } from '@vueuse/shared';
import { Vec2 } from './interfaces';
export const vec2Length = ([x, y]: Vec2) => Math.abs(Math.sqrt(x * x + y * y));
@ -7,11 +8,22 @@ export const vec2Add = ([x1, y1]: Vec2, [x2, y2]: Vec2): Vec2 => [
y1 + y2,
];
export const vec2Multiply = ([x1, y1]: Vec2, [x2, y2]: Vec2): Vec2 => [
x1 * x2,
y1 * y2,
];
export const vec2Sub = ([x1, y1]: Vec2, [x2, y2]: Vec2): Vec2 => [
x1 - x2,
y1 - y2,
];
export const vec2Clamp = (
[x1, y1]: Vec2,
[x2, y2]: Vec2,
[x3, y3]: Vec2
): Vec2 => [clamp(x1, x2, x3), clamp(y1, y2, y3)];
export const vec2MultiplyScalar = ([x, y]: Vec2, scalar: number): Vec2 => [
x * scalar,
y * scalar,