Web Dev Solutions

Catalin Mititiuc

From b443b37a1110866db1352cf201f14f1916cd217b Mon Sep 17 00:00:00 2001 From: Catalin Mititiuc Date: Mon, 22 Apr 2024 11:43:31 -0700 Subject: Update storing pan & zoom changes to localStorage --- src/index.js | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/src/index.js b/src/index.js index 84001d4..cb746f4 100644 --- a/src/index.js +++ b/src/index.js @@ -2,36 +2,31 @@ import { pan, zoom } from 'svg-pan-zoom'; import Game from './modules/game.js'; const PanZoom = new function () { - const vb = 'viewBox'; - let svg; + const storageKey = 'pan-zoom'; - function storeViewBoxVal() { - localStorage.setItem(vb, svg.getAttribute(vb)); + function storePanZoomVal(transformMatrix) { + localStorage.setItem(storageKey, transformMatrix); } - function observeViewBoxChanges() { - const observer = new MutationObserver(mutations => { - if (mutations.find(m => m.target == svg && m.attributeName == vb)) { - storeViewBoxVal(svg); - } - }); + function observePanZoomChanges(svg) { + const observer = new MutationObserver(() => storePanZoomVal(svg.style.transform)); - observer.observe(svg, { attributes: true }); + observer.observe(svg, { attributeFilter: ['style'] }); } - function restoreViewBoxVal() { - const storedVbVal = localStorage.getItem(vb); + function restorePanZoomVal(svg) { + const storedPanZoomVal = localStorage.getItem(storageKey); - if (storedVbVal) { - svg.setAttributeNS(null, vb, storedVbVal); + if (storedPanZoomVal) { + svg.style.transform = storedPanZoomVal; } } - function addEventListeners() { + function addEventListeners(svg) { svg.addEventListener('wheel', e => { e.preventDefault(); - svg.setAttributeNS(null, vb, zoom(svg, e)); + zoom(svg, e); }, { passive: false }); svg.addEventListener('pointerdown', e => { @@ -41,11 +36,10 @@ const PanZoom = new function () { }, { passive: false }); } - this.start = function (el) { - svg = el; - restoreViewBoxVal(); - addEventListeners(); - observeViewBoxChanges(); + this.start = function (svg) { + restorePanZoomVal(svg); + addEventListeners(svg); + observePanZoomChanges(svg); }; }; -- cgit v1.2.3