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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.