2017-11-17 11 views
2

D3でズームがどのように動作するか、具体的にどのように呼び出され、設定が初期化されたかを理解するのに問題があります。上のズーム機能を複数回呼び出すすることが必要であるのはなぜD3ズーム設定

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]) 
} 

:私はD3 V4にマニング教科書からのものであり、正常に動作します以下のコードスニペットを(のみ不可欠ビットが含まれている)、持っていますsvg?初めて呼び出されたときは、「zoomSettings」と2回目に渡します。これのポイントは何ですか?ズームイベントは、すべてのパスを保持するグループではなく、SVGで動作しているという事実と関係がありますか?私は、SVGに呼ばれているこのようなズームのはるかに簡単な例に慣れていると、要素がグループにバインドされています

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^ 

任意の明確化の誰かがいただければ幸いこれに提供することができます。私はAPIにもかかわらず、D3のzoom()が非常に混乱していることがわかりました。

答えて

2

このライン:

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

は、2つの別々のことをやっています。

まず、svg.call(mapZoom)applying the zoom behaviorからsvgです。 2番目の呼び出し、.call(mapZoom.transform, zoomSettings)は、svgに対してprogrammatically setting a zoom transformです。これは、ユーザーが何かをする前の初期状態を設定しています。

だから、このようにそれについて考える:

  1. ズーム動作(var zoom = d3.zoom()
  2. を作成SVG要素(svg.call(mapZoom)
  3. にそれを適用して初期状態(.call(mapZoom.transform, zoomSettings)
を設定します。
関連する問題