javascript - D3 变焦设置

标签 javascript d3.js svg event-handling

我在理解 D3 中缩放的工作原理时遇到一些困难,特别是它是如何调用的以及如何初始化设置的。我有以下代码片段(仅包含必要的部分),该代码来自 D3 V4 上的曼宁教科书,并且运行良好:

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)

function createMap(countries, cities) {
    var projection = d3.geoMercator()
        .scale(scale)
        .translate([width/2,height/2])

var mapZoom = d3.zoom()
    .on("zoom", zoomed)

var zoomSettings = d3.zoomIdentity
    .translate(width/2, height/2)
    .scale(scale)

svg.call(mapZoom).call(mapZoom.transform, zoomSettings) // ?!!!

function zoomed() {
        var e = d3.event
        .translate([e.transform.x, e.transform.y])
        .scale(e.transform.k)

    // I didn't include the drawing of the paths, but 
       they are appended to the SVG, and this updates their data.

    d3.selectAll("path.graticule").attr("d", geoPath)
    d3.selectAll("path.countries").attr("d", geoPath)
    d3.selectAll("circle.cities")
    .attr("cx", d => projection([d.x,d.y])[0])
    .attr("cy", d => projection([d.x,d.y])[1])
}

为什么需要在 svg 上多次调用缩放函数? 第一次调用时,我们不传递“zoomSettings”,第二次调用时我们的确是。这有什么意义?这是否与缩放事件在 SVG 上工作,而不是在保存我所有路径的组上有关?我习惯了像这样更简单的缩放示例,它们在 SVG 上调用,并且元素绑定(bind)到一个组:

var zoom = d3.zoom()
    .scaleExtent([1,3])
    .on("zoom", zoomed)

function zoomed(){
    g.attr("transform", d3.event.transform)
}

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)
    .call(zoom)

var g = d3.select("svg").append("g")

// All elements are bound to group^

如果有人能对此提供任何澄清,我们将不胜感激。我发现 D3 中的 Zoom() 非常令人困惑,尽管有 API。

最佳答案

这一行:

svg.call(mapZoom).call(mapZoom.transform, zoomSettings)

正在做两件不同的事情。

首先,svg.call(mapZoom)applying the zoom behaviorsvg。第二个调用 .call(mapZoom.transform, ZoomSettings)programmatically setting a zoom transform到 svg。这是在用户对其执行任何操作之前设置其初始状态。

所以想一下:

  1. 创建缩放行为 (var Zoom = d3.zoom())
  2. 将其应用于 svg 元素 (svg.call(mapZoom))
  3. 设置其初始状态 (.call(mapZoom.transform, ZoomSettings))

关于javascript - D3 变焦设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355935/

相关文章:

javascript - 语义缩放和平移 d3.js v4

javascript - 如何将 html 作为文本添加到 d3.js 树节点

css - 如何在 Bootstrap 4 中使用 Font Awesome 中的 svg 图标?

javascript - 有没有办法在单击扩展程序图标时添加 HTML

javascript - OrientDB:如何在服务器端函数中检查查询结果是否不为空?

javascript - 更改选择框中的数据

javascript - D3 (v3) 在单击另一个圆后重置先前的动画圆

javascript - 我无法在 javascript 中将对象从字符串解析为对象

pdf - 如何在 iReport 中嵌入和显示 SVG 图像

javascript - 从数组嵌套 JSON