zoom-element
Version:
[]() [](https://github.com/spyder01/zoom-element/issues) [ • 2.88 kB
JavaScript
class ZoomAreaException extends DOMException {
constructor(msg = "An error occured while creating zoom area.") {
super(msg);
}
}
const defaultZoomAreaConfig = {
minZoom: 0.2,
maxZoom: 2.5,
initialScale: 1,
zoomScale: 0.1
};
class ZoomArea {
constructor(id = "zoom-area", config = defaultZoomAreaConfig) {
this.getScale = () => this.scale;
this.zoom = (delta) => {
const newScale = this.scale + delta;
this.scale = Math.max(this.minZoom, Math.min(this.maxZoom, newScale));
this.setDivStyle();
return this;
};
this.zoomIn = () => this.zoom(this.zoomScale);
this.zoomOut = () => this.zoom(-this.zoomScale);
this.reset = () => {
this.position = { x: 0, y: 0 };
this.scale = this.config.initialScale;
this.setDivStyle();
return this;
};
this.handleDrag = (e) => {
console.log("hello");
if (this.isDragging) {
const dx = e.clientX - this.initialPosition.x;
const dy = e.clientY - this.initialPosition.y;
const { x, y } = this.position;
this.position = {
x: x + dx,
y: y + dy
};
this.initialPosition = {
x: e.clientX,
y: e.clientY
};
}
this.setDivStyle();
};
this.handleCntrlWheel = (e) => {
if (!e.ctrlKey) {
return;
}
this.initialPosition.y += e.deltaY;
this.position.y += e.deltaY;
};
this.setDivStyle = () => {
this.zoomArea.style.transform = `scale(${this.scale}) translate(${this.position.x}px, ${this.position.y}px)`;
this.zoomArea.style.transformOrigin = "center";
};
this.init = () => {
this.setDivStyle();
this.zoomArea.addEventListener("mousemove", this.handleDrag);
this.zoomArea.addEventListener("mouseup", () => this.isDragging = false);
this.zoomArea.addEventListener("mousedown", (e) => {
this.isDragging = true;
this.initialPosition = {
x: e.clientX,
y: e.clientY
};
this.setDivStyle();
});
this.zoomArea.addEventListener("wheel", this.handleCntrlWheel);
};
this.zoomArea = document.getElementById(id);
this.scale = config.initialScale ? config.initialScale : defaultZoomAreaConfig.initialScale;
this.minZoom = config.minZoom ? config.minZoom : defaultZoomAreaConfig.minZoom;
this.maxZoom = config.maxZoom ? config.maxZoom : defaultZoomAreaConfig.maxZoom;
this.initialPosition = { x: 0, y: 0 };
this.position = this.initialPosition;
this.isDragging = false;
this.zoomScale = config.zoomScale ? config.zoomScale : defaultZoomAreaConfig.zoomScale;
this.config = {
...defaultZoomAreaConfig,
...config
};
if (!this.zoomArea) {
throw new ZoomAreaException();
}
this.init();
}
}
export { ZoomAreaException, ZoomArea as default };