简体   繁体   中英

How do I disable my zoom functionality in D3.js?

I have a zoom functionality made in D3, but I'd like to make it optional, so I'd like a way to turn it off. Here's my code:

//Zoom command ...
var zoom = d3.behavior.zoom()
    .x(xScale)
    .y(yScale)
    .scaleExtent([1,10])
    .on("zoom", zoomTargets);

var SVGbody = SVG.append("g")
    .attr("clip-path", "url(#clip)")
    .call(zoom);

/

/The function handleling the zoom. Nothing is zoomed automatically, every elemnt must me defined here.
function zoomTargets() {
    if($("#enableZoom").is(':checked')){    
        var translate = zoom.translate(),
        scale = zoom.scale();

        tx = Math.min(0, Math.max(width * (1 - scale), translate[0]));
        ty = Math.min(0, Math.max(height * (1 - scale), translate[1]));

        //This line applies the tx and ty which prevents the graphs from moving out of the limits. This means it can't be moved until zoomed in first.
        zoom.translate([tx, ty]);

        SVG.select(".x.axis").call(xAxis)
            .selectAll("text")
                .style("text-anchor", "end")
                .style("font-size", AXIS_FONTSIZE)
                .attr("transform", function(d) {
                return "rotate(-30)" 
                });

        SVG.select(".y.axis").call(yAxis)
            .selectAll("text")
                .style("font-size", AXIS_FONTSIZE);

        SVG.selectAll("circle")
        .attr("cx", function(d, i){ return xScale(graphDataX[i]);})
        .attr("cy",function(d){return yScale(d);});

        SVGMedian.selectAll("ellipse")
            .attr("cx", function(d, i){ return xScale((i*100)+100);})
            .attr("cy", function(d){ return yScale(d-0.01);});
    }
}

As you can see I tried using an if-statement to prevent the zoom functionality from working when a checkbox isn't ticked. This prevents users from scrolling on the page when the mouse is inside of the SVG frame.

I'd like the correct way to do this. Thanks very much in advance!

这是一种禁用d3缩放行为的方法

SVGbody.select("g").call(d3.behavior.zoom().on("zoom", null));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM