1

My web project needs to zoom a div element around the mouse position as anchor while mouse wheeling, I was inspired by @Tatarize 's answer at Zoom in on a point (using scale and translate), but I can't implement it exactly, it can't zoom and translate around the mouse position, can any one help?

window.onload = function() {
    const STEP = 0.05;
    const MAX_SCALE = 10;
    const MIN_SCALE = 0.01;

    const red = document.getElementById('red');
    const yellow = red.parentNode;

    let scale = 1;

    yellow.onmousewheel = function (event) {
        event.preventDefault();
        
        let mouseX = event.clientX - yellow.offsetLeft - red.offsetLeft;
        let mouseY = event.clientY - yellow.offsetTop - red.offsetTop;

        const factor = event.wheelDelta / 120;

        const oldScale = scale;
        scale = scale + STEP * factor;
        scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));

        const scaleChanged = scale - oldScale;
        const offsetX = -(mouseX * scaleChanged);
        const offsetY = -(mouseY * scaleChanged);

        console.log(offsetX, offsetY);

        red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
    }
}
.yellow {
    background-color: yellow;
    width: 400px;
    height: 200px;
}

.red {
    background-color: red;
    width: 100px;
    height: 50px;
}
<div class="yellow">
    <div id="red" class="red"></div>
</div>
Suge
  • 2,808
  • 3
  • 48
  • 79
  • My code given there is to change the viewbox with regard to a zoom point. You are moving the rectangle based on some math that has no bearing on that at all. The idea is to pan the zoom box with regard to the change in the scale. You are changing the position and location of a rectangle. Which is to say you need to simulate the new position of the red rectangle with regard to yellow rectangle as if it were a viewport, keeping in mind that when it weirdly moves out of frame it'll resize the actual viewport. – Tatarize Jan 04 '18 at 17:20

3 Answers3

5

Really incredible, I actually did it.

window.onload = () => {
    const STEP = 0.99;
    const MAX_SCALE = 5;
    const MIN_SCALE = 0.01;

    const red = document.getElementById("red");
    const yellow = red.parentNode;

    let scale = 1;

    const rect = red.getBoundingClientRect();
    const originCenterX = rect.x + rect.width / 2;
    const originCenterY = rect.y + rect.height / 2;

    yellow.onwheel = (event) => {
        event.preventDefault();

        const factor = event.deltaY;

        // If current scale is equal to or greater than MAX_SCALE, but you're still zoom in it, then return;
        // If current scale is equal to or smaller than MIN_SCALE, but you're still zoom out it, then return;
        // Can not use Math.max and Math.min here, think about it.
        if ((scale >= MAX_SCALE && factor < 0) || (scale <= MIN_SCALE && factor > 0)) return;
        
        const scaleChanged = Math.pow(STEP, factor);
        scale *= scaleChanged;

        const rect = red.getBoundingClientRect();
        const currentCenterX = rect.x + rect.width / 2;
        const currentCenterY = rect.y + rect.height / 2;

        const mousePosToCurrentCenterDistanceX = event.clientX - currentCenterX;
        const mousePosToCurrentCenterDistanceY = event.clientY - currentCenterY;

        const newCenterX = currentCenterX + mousePosToCurrentCenterDistanceX * (1 - scaleChanged);
        const newCenterY = currentCenterY + mousePosToCurrentCenterDistanceY * (1 - scaleChanged);

        // All we are doing above is: getting the target center, then calculate the offset from origin center.
        const offsetX = newCenterX - originCenterX;
        const offsetY = newCenterY - originCenterY;

        // !!! Both translate and scale are relative to the original position and scale, not to the current.
        red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
    }
}
.yellow {
  background-color: yellow;
  width: 200px;
  height: 100px;

  margin-left: 50px;
  margin-top: 50px;

  position: absolute;
}

.red {
  background-color: red;
  width: 200px;
  height: 100px;

  position: absolute;
}
<div class="yellow">
    <div id="red" class="red"></div>
</div>
Suge
  • 2,808
  • 3
  • 48
  • 79
  • if (factor > 0) { var scaleChanged = 1.05; } else { var scaleChanged = .95; } Yeah, totally works. Nicely done. I was notably kind of annoyed with it, as mine should have worked but was always off by a little bit and I couldn't find the issue. – Tatarize Jan 08 '18 at 17:59
  • @Suge I'm having a hard time understanding the Math.pow and (1-scaleChanged) thing... can you please explain what's going on and why? Oh, and thanks for the amazing solution! – Ahmad Al Haddad Jan 15 '20 at 17:12
1

.onmousewheel is deprecated. Use .onwheel instead.

Also, onwheel event doesn't have wheelDelta property. Use deltaY.

Kamil Weber
  • 126
  • 1
  • 9
1

My code given there is to change the viewbox with regard to a zoom point. You are moving the rectangle based on some math that doesn't fit that situation.

The idea is to pan the zoom box with regard to the change in the scale. You are changing the position and location of a rectangle. Which is to say you need to simulate the new position of the red rectangle as if the yellow rectangle were a viewport. Which means that when we zoom in, we are zooming in at a translateX translateY position of a particular scale factor. We then need to translate the value of the zoom point into the right scene space. Then adjust the position of the red rectangle as if it were in that scene space.

Here's the code with some corrections, though I'm clearly missing a few elements. The big thing is the lack of preservation of the translateX translateY stuff. You overwrite it so it ends up just preserving the zoom and screwing up the translateX, translateY stuff back to zero when it's a relative offset of the viewport.

In functional code, zooming in in the rectangle will make the red rectangle fill the entire scene space.

window.onload = function() {
    const STEP = 0.05;
    const MAX_SCALE = 10;
    const MIN_SCALE = 0.01;

    const red = document.getElementById('red');
    const yellow = document.getElementById('yellow');
    const svgArea = document.getElementById('svgArea');

    let viewportTranslateX = 0;
    let viewportTranslateY = 0;
    let viewportScale = 1;

    svgArea.onwheel = function (event) {
        event.preventDefault();
        console.log("mouse coords", event.clientX, event.clientY);
         
        let zoompointX = (event.clientX + (viewportTranslateX / viewportScale)) * viewportScale;
        let zoompointY = (event.clientY + (viewportTranslateY / viewportScale)) * viewportScale;
        console.log("zoom point prezoom", zoompointX, zoompointY);
        
        const factor = event.deltaY / 120;

        const oldScale = viewportScale;
        viewportScale = viewportScale * (1 + STEP * factor);
        viewportScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, viewportScale));

        const scaleChanged = viewportScale - oldScale;
        const offsetX = -(zoompointX * scaleChanged);
        const offsetY = -(zoompointY * scaleChanged);
        console.log("scale", scaleChanged, offsetX, offsetY);
        viewportTranslateX += offsetX;
        viewportTranslateY += offsetY;

        zoompointX = (event.clientX + (viewportTranslateX / viewportScale)) * viewportScale;
        zoompointY = (event.clientY + (viewportTranslateY / viewportScale)) * viewportScale;
        console.log("zoompoint postzoom", zoompointX, zoompointY);

        var x = viewportTranslateX;
        var y = viewportTranslateY;
        var width = (svgArea.getAttribute("width") * viewportScale);
        var height = (svgArea.getAttribute("height") * viewportScale);

        svgArea.setAttribute("viewBox", x + " " + y + " " + width + " " + height);
        console.log("viewport", x, y, width, height, viewportScale);
    }
}
<svg id="svgArea" width=400 height=200 viewBox="0,0,400,200">
   <rect id="yellow" width=400 height=200 fill="yellow"/>
   <rect id="red" width=100 height=50 fill="red"/>
</svg>
Tatarize
  • 10,238
  • 4
  • 58
  • 64
  • Thank you but sorry I haven't quite understood it, the code you corrected still doesn't work, did I do something wrong? – Suge Jan 05 '18 at 12:41
  • I corrected some aspects of it, I tried some more but still couldn't get it to work either. It somehow gets off kilter and I can't get the mouseX mouseY to properly fit the scene relative locations. – Tatarize Jan 05 '18 at 12:57
  • I corrected a good chunk of it. It's closer but beyond translating the zoompoint successfully into the scene space I also need it to remain constant pre and post zoom. I'm hammered down one aspect without the other aspect kicking in. In reality most systems you'd care about for graphics here you'd just directly use a matrix or affinetransform class and end up keeping things properly in sync that way. – Tatarize Jan 05 '18 at 15:42
  • Thank you Tatarize, please take a look at my answer, it looks like that way works. – Suge Jan 07 '18 at 12:42
  • @Suge That is certainly functional. Though it seems like a required zoomfactor of 2x is not very standard and might be blocking some very minor shifting which has haunted several of these implementations. – Tatarize Jan 08 '18 at 17:54