d3js zooming groups of circles

喜夏-厌秋 提交于 2020-01-17 04:57:25

问题


I am trying d3.js zoom behavior for the first time, I am quite struggling to get it worked. My requirement is to have a zoom in, zoom out behaviour in a svg element where browser's zoom behaviour should be disabled and only the circles inside the svg should increase/decrease its radius upon zoom in/out.

In summary, when the user scrolls the mouse the svg width, height should not change. Just the circles should change its radius.

This is what I have now, can anyone help me to fill it in?

<g>
    <circle id='top' cx="180" cy="120" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
    <circle id='top' cx="200" cy="220" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
    <circle id='top' cx="320" cy="150" r="50" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>

var zoom = d3.behavior.zoom()
            .scaleExtent([1, 8])
            .on("zoom", function () {

            console.log('zooming');

            var graph = d3.select('svg');

            graph
                .selectAll('g')
                .attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");


        });



    var svg = d3.select('svg').append('g').call(zoom);

回答1:


Bind the zoom listener to the SVG instead of the new group.

Change following line of code

var svg = d3.select('svg').append('g').call(zoom);

To

var svg = d3.select('svg').call(zoom);

Complete Code:

var zoom = d3.behavior.zoom()
  .scaleExtent([1, 8])
  .on("zoom", function() {    
    var graph = d3.select('svg');
    graph
      .selectAll('g')
      .attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
  });
var svg = d3.select('svg').call(zoom);

Here is the working JSFiddle



来源:https://stackoverflow.com/questions/33901553/d3js-zooming-groups-of-circles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!