gpt4 book ai didi

javascript - 使用 d3.behavior.zoom 平移/缩放到特定组 ID/getBBox()

转载 作者:行者123 更新时间:2023-11-30 00:19:50 26 4
gpt4 key购买 nike

我正在尝试使用 d3.behavior.zoom() 制作交互式平移/缩放 SVG 平面图/ map 功能。我的代码大致基于 Zoom to Bounding Box II .

我正在通过 $.get() 异步加载 svg然后使用 button.on('click')处理程序以获取 .getBBox()具体的 <g>按元素 ID,#g-1101 (在 svg 上表示为红色圆圈)。然后我想将 svg 的视口(viewport)居中到 #g-1101 的中间的边界框。

作为粗略的尝试,我只是想翻译顶级 svg > g通过使用 g#1101.getBBox().x && .getBBox().y .在我看来,我的数学不合格。

我试过合并 (svg.node().getBBox().width / 2) - scale * g.getBBox().x)将边界框的中间点居中到视口(viewport),但它的平移甚至不在球场上。

代码

(function(){

var svg, g; $.get('http://layersofcomplexity.com/__fp.svg', function(svg){
$('body').append($(svg));
init();
},'text');

function init() {

console.log('init');

svg = d3.select('svg');
g = d3.select('svg > g');

var zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([1, 8])
.on("zoom", zoomed);

svg
.call(zoom)
.call(zoom.event);

$('.pan').on('click', function(){
// var id = '#g-1011';
var scale = 4;
var bbox = $('#g-1101')[0].getBBox();
// d3.select(id).node().getBBox();
var x = bbox.x;
var y = bbox.y;
// var scale = .9 / Math.max(dx / width, dy / height),
// var translate = [width / 2 - scale * x, height / 2 - scale * y];
var width = svg.node().getBBox().width;
var height = svg.node().getBBox().height;
var translate = [-scale*x,-scale*y];
g.transition().duration(750) .call(zoom.translate(translate).scale(scale).event);
});

}

function zoomed() {
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

})();

-- EDIT JSBin 坏了 --

我错过了什么? JSBin .

最佳答案

代码中的一个小改动,使标记以红色居中 g#g-1101

  var bbox = $('#g-1101')[0].getBBox(); 


var x = bbox.x-((bbox.width));
var y = bbox.y-((bbox.height));
//scale should be 1 less
var translate = [-(x*(scale-1)),-(y*(scale-1))];

工作代码here

希望对你有帮助

关于javascript - 使用 d3.behavior.zoom 平移/缩放到特定组 ID/getBBox(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587735/

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