Search code examples
javascriptd3.jssvgzooming

How to add the filter or ScaleExtent in d3 v4 in Timeline with Zoom functionality


I am working on timeline in d3 version 4. So i have created a SVG and added the axis and zoom on that SVG as below.

var timeLineSVG = d3.select("body")
                .append("svg")
                .attr("width", 300)
                .attr("height", 300);
var xScale = d3.scaleTime()
            .domain([Date.parse("April 1, 2017"), Date.parse("April 30, 2017")])
            .range([0, 300]);

var xAxis = d3.axisTop(xScale);

var timeLineZoom = d3.zoom(xScale)
                    .on("zoom", onTimeLineZoom);

var timeLineGraphics = timeLineSVG.append("g")
                                .attr("transform", "translate(0,40)")
                                .call(xAxis);
timeLineSVG.call(timeLineZoom);

function onTimeLineZoom(event) {
    var tempScale = d3.event.transform.rescaleX(xScale);
    timeLineGraphics.call(xAxis.scale(tempScale));
}

The domain and range for the scale is going to change based on the data. So I want to allow zoom only till day level not beyond the day level.

Here is the small example what I have done.

We can use the scaleextent property on the zoom instance but what is the value and how can we calculate with out hard coding.


Solution

  • You can use scaleExtend([minScaleFactor, maxScaleFactor]) to control it. Example: d3.zoom().scaleExtend([0.5, 10])