我正在使用这个 SVG 平移缩放库:https://github.com/bumbu/svg-pan-zoom
我为你准备了CodePen:https://codepen.io/ItsBenedict/pen/vYMbjpK
如果单击某个类别,该组应以视口为中心。我在这里使用的相关代码是从第 36 行开始的。
var button1 = document.getElementById("cat-1")
button1.addEventListener("click", function() {
const { left, width, top, height } = button1.getBoundingClientRect();
customPanBy({x: width/2 - left, y: height/2 - top});
});
目前该组正在移动到左上角,所以我猜计算是错误的。看起来我需要使用这个插件的 getSizes 但我不知道如何使用它。这是另一个问题,但我对 JavaScript 并没有真正的经验,所以我无法自己让它工作:svg-pan-zoom 平移/缩放到任何对象
如果有人可以帮助我,我将不胜感激!
我认为宽度和高度值有点令人困惑 - 您是根据按钮本身的宽度和高度进行计算的。这是修复后的JS计算,使用窗口innerHeight和innerWidth
function customPanBy(amount){ // {x: 1, y: 2}
var animationTime = 300 // ms
, animationStepTime = 15 // one frame per 30 ms
, animationSteps = animationTime / animationStepTime
, animationStep = 0
, intervalID = null
, destX = (window.innerWidth/2) - amount.x
, destY = (window.innerHeight/2) - amount.y
, stepX = destX / animationSteps
, stepY = destY / animationSteps
intervalID = setInterval(function(){
if (animationStep++ < animationSteps) {
panZoom.panBy({x: stepX, y: stepY})
} else {
// Cancel interval
clearInterval(intervalID)
}
}, animationStepTime)
}
以及按钮代码的更新
var button1 = document.getElementById("cat-1")
button1.addEventListener("click", function() {
const { left, width, top, height } = button1.getBoundingClientRect();
customPanBy({x: left, y: top});
});