如何使用鼠标滚轮使用viewBox缩放SVG

问题描述 投票:0回答:1

我想使用鼠标滚轮来控制缩放比例并使用SVG的viewBox属性来转换图像来在SVG图像上创建缩放效果。

用鼠标滚轮缩放后,我希望鼠标下方的点保持在鼠标下方的同一位置。

javascript svg zooming viewbox
1个回答
4
投票
window.addEventListener("DOMContentLoaded", (event) => {
    const svg = document.querySelector('svg');

    // zooming
    svg.onwheel = function (event) {
        event.preventDefault();

        // set the scaling factor (and make sure it's at least 10%)
        let scale = event.deltaY / 1000;
        scale = Math.abs(scale) < .1 ? .1 * event.deltaY / Math.abs(event.deltaY) : scale;

        // get point in SVG space
        let pt = new DOMPoint(event.clientX, event.clientY);
        pt = pt.matrixTransform(svg.getScreenCTM().inverse());

        // get viewbox transform
        let [x, y, width, height] = svg.getAttribute('viewBox').split(' ').map(Number);

        // get pt.x as a proportion of width and pt.y as proportion of height
        let [xPropW, yPropH] = [(pt.x - x) / width, (pt.y - y) / height];
        
        // calc new width and height, new x2, y2 (using proportions and new width and height)
        let [width2, height2] = [width + width * scale, height + height * scale];
        let x2 = pt.x - xPropW * width2;
        let y2 = pt.y - yPropH * height2;        

        svg.setAttribute('viewBox', `${x2} ${y2} ${width2} ${height2}`);
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.