Web Dev Solutions

Catalin Mititiuc

From a715a966f66e538ecef949e6de286cbf8617740f Mon Sep 17 00:00:00 2001 From: Catalin Mititiuc Date: Thu, 28 Mar 2024 10:32:17 -0700 Subject: Pan the map when clicked and dragged --- index.js | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) (limited to 'index.js') diff --git a/index.js b/index.js index faa9e9c..fe9b23f 100644 --- a/index.js +++ b/index.js @@ -396,8 +396,8 @@ svg.addEventListener('wheel', e => { let newY = e.deltaY < 0 ? y + yChange : y - yChange; let newHeight = e.deltaY < 0 ? height - yChange - heightChange : height + yChange + heightChange; - console.log('VIEWBOX_X', 'VIEWBOX_Y', VIEWBOX_X, VIEWBOX_Y); - console.log('VIEWBOX_WIDTH', 'VIEWBOX_HEIGHT', VIEWBOX_WIDTH, VIEWBOX_HEIGHT); + // console.log('VIEWBOX_X', 'VIEWBOX_Y', VIEWBOX_X, VIEWBOX_Y); + // console.log('VIEWBOX_WIDTH', 'VIEWBOX_HEIGHT', VIEWBOX_WIDTH, VIEWBOX_HEIGHT); // if (newWidth + newX > VIEWBOX_WIDTH + VIEWBOX_X && newX < VIEWBOX_X) { // newWidth = VIEWBOX_WIDTH; @@ -419,4 +419,45 @@ svg.addEventListener('wheel', e => { // newY = newY < VIEWBOX_Y ? VIEWBOX_Y : newY; svg.setAttributeNS(null, 'viewBox', `${newX} ${newY} ${newWidth} ${newHeight}`); -}, { passive: false }); \ No newline at end of file + console.log('viewbox after wheel', svg.viewBox.baseVal); +}, { passive: false }); + +svg.addEventListener('mousedown', e => { + const minPanDistanceThreshold = 5; + + let dist, ctm, + pan = false, + { x, y, width, height } = svg.viewBox.baseVal, + startPt = new DOMPoint(e.clientX, e.clientY), + movePt = new DOMPoint(); + + function mouseMove(e) { + movePt.x = e.clientX; + movePt.y = e.clientY; + dist = Math.sqrt((movePt.x - startPt.x)**2 + (movePt.y - startPt.y)**2); + + if (!pan && dist >= minPanDistanceThreshold) { + pan = true; + startPt.x = e.clientX; + startPt.y = e.clientY; + } + + if (pan) { + ctm = svg.getScreenCTM().inverse(); + + const [svgStartPt, svgMovePt] = [startPt, movePt].map(p => p.matrixTransform(ctm)), + moveX = svgStartPt.x - svgMovePt.x + x, + moveY = svgStartPt.y - svgMovePt.y + y; + + svg.setAttributeNS(null, 'viewBox', `${moveX} ${moveY} ${width} ${height}`); + } + } + + function mouseUp() { + document.removeEventListener('mousemove', mouseMove); + svg.removeEventListener('mouseup', mouseUp); + } + + document.addEventListener('mousemove', mouseMove); + svg.addEventListener('mouseup', mouseUp); +}); \ No newline at end of file -- cgit v1.2.3