Software zoom is a daunting task in the D3 library, since D3 scaling is closely related to mouse events. A common example of software scaling is zooming in or out with the slider. Surprisingly, I could not find a single working example of how to make D3 scaling work using the slider. After some time and effort, I developed this working demo, which can be found here D3SliderZoom . The key point is to change the conversion attribute "<g>" SVGElement, embedded in the "<svg>" element, using the scale value specified by the slider.
function zoomWithSlider(scale) { var svg = d3.select("body").select("svg"); var container = svg.select("g"); var h = svg.attr("height"), w = svg.attr("width"); // Note: works only on the <g> element and not on the <svg> element // which is a common mistake container.attr("transform", "translate(" + w/2 + ", " + h/2 + ") " + "scale(" + scale + ") " + "translate(" + (-w/2) + ", " + (-h/2) + ")");
}
This method should then be called from the slider change event, as shown below.
$(function() { $( "#slider-vertical" ).slider({ orientation: "vertical", range: "min", min: 1000, max: 10000, value: 1000, slide: function( event, ui ) { zoomWithSlider(ui.value/1000); } });
});
This solution is much more elegant than creating a pseudo-mouse scroll.
source share