I want to add a mousewheel zoom to my sunburst:
What I did is I edited this piece of code:
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height * .52 + ")")
.call(zoom);
function zoomed() {
svg.attr('transform', 'translate(' + d3.event.transform.x + ',' + d3.event.transform.y + ') scale(' + d3.event.scale + ')');
//svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
The problem is that when the page loads everything seems to be ok, however when the mouswheel is used to scroll the sunburst ends up in the upper left corner:
I was able to fix this by changing this code:
function zoomed() {
svg.attr("transform", "translate(" + width/2 + "," + height * .52 + ")scale(" + d3.event.scale + ")");
}
The sunburst stays in the middle now, however this won't zoom to the place of the cursor and won't allow the user to zoom out further.
Any suggestions how I can zoom to the cursor place (as in the first code example) without the sunburst disapering in the upper left corner?
For the full code see JSfiddle, it's not working here, however running it local does work.
d3.event.translate
returns an array. Thus, if you want to add those values (width/2
and height/2
), you have to add them separately:
function zoomed() {
svg.attr('transform', 'translate(' + (d3.event.translate[0] + width / 2) +
',' + (d3.event.translate[1] + height / 2) + ') scale(' + d3.event.scale + ')');
}
Alternatively, if you want to use your original zoomed function...
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate +
")scale(" + d3.event.scale + ")");
}
... just break the svg selection, assigning another name for the group:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var foo = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height * .52 + ")")
.call(zoom);