gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:55:29 28 4
gpt4 key购买 nike

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

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

最佳答案

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}`);
}
})

关于javascript - 如何使用 viewBox 使用鼠标滚轮缩放 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76150884/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com