Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mouse click and drag to zoom in D3

I'm new to D3 and would like to implement a click-drag-zoom similar to what is shown here: http://www.highcharts.com/demo/line-time-series

I already have a line graph I have built, but am confused as to how to implement this.

I guess I need some JS event handlers to find where my mousedown and mouseup happens. But how do I create the shading that occurs on the graph when the user is dragging?

like image 261
wynnch Avatar asked Oct 07 '22 08:10

wynnch


1 Answers

You'll probably want to use a brush to do this in d3.js. You can see an example that I put together at http://bl.ocks.org/1962173 which does something similar.

The relevant code is:

var brush = d3.svg.brush()
    .x(x)
    .extent([d3.time.monday(now),d3.time.saturday.ceil(now)])
    .on("brush", display);

where display is a function that redraws data based on the current extent of brush. This way you don't need to try and hook your own handlers or even worry about resizing the highlighted region at all.

like image 195
Bill Avatar answered Oct 13 '22 12:10

Bill