Web Dev Solutions

Catalin Mititiuc

From 2d3fc1cd22ffcc61ec178eeaf97f3a4d7cba98bf Mon Sep 17 00:00:00 2001 From: Catalin Mititiuc Date: Sat, 20 Apr 2024 19:34:06 -0700 Subject: Use CSS transformations instead of manipulating the viewBox --- src/app.js | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) (limited to 'src/app.js') diff --git a/src/app.js b/src/app.js index f5a4fa8..3afc329 100644 --- a/src/app.js +++ b/src/app.js @@ -1,18 +1,31 @@ import zoom from './modules/zoom.js'; import pan from './modules/pan.js'; -window.addEventListener('load', function () { - const svg = document.querySelector('object').contentDocument.querySelector('svg'); +const optionalZoomFactor = 0.1, + container = document.querySelector('.container'), + object = document.querySelector('object'), + img = document.querySelector('img'), + button = document.querySelector('button'); + +function reset(elements) { + elements.forEach(el => el.removeAttribute('style')); +} - svg.addEventListener('wheel', e => { - e.preventDefault(); +// If embedding an SVG using an tag, it's necessary to wait until the +// page has loaded before querying its `contentDocument`, otherwise it will be +// `null`. - svg.setAttributeNS(null, 'viewBox', zoom(svg, e)); - }, { passive: false }); +window.addEventListener('load', function () { + const svg = object.contentDocument.querySelector('svg'), + pannableAndZoomableElements = [img, svg]; - svg.addEventListener('pointerdown', e => { - e.preventDefault(); + button.addEventListener('click', () => { + [button, container].forEach(el => el.classList.toggle('switch')); + reset(pannableAndZoomableElements); + }); - pan(svg, e); - }, { passive: false }); + pannableAndZoomableElements.forEach(el => { + el.addEventListener('wheel', e => zoom(el, e, optionalZoomFactor), { passive: false }); + el.addEventListener('pointerdown', e => pan(el, e), { passive: false }); + }); }); -- cgit v1.2.3