Snake Eyes
Snake Eyes

Reputation: 16764

Add svg pan zoom to dynamically created svg with D3js

For pan and zoom I use this library.

So, when I right click, I create a new SVG element with D3js library like:

$("body").on("contextmenu", function(e) {
        var parent = d3.select("#panzoom");
        var id = "svg"+($("#panzoom svg").length+1);

        var svg = parent.append("svg").attr("width", 200+"px").attr("height", 200+"px").attr("x", e.pageX+"px").attr("y", e.pageY+"px").attr("id", id);
        var rectSelection = svg.append("rect")
        .attr("x", e.pageX)
        .attr("y", e.pageY)
        .attr("width", 200)
        .attr("height", 200)
        .attr("fill", "yellow");

       // here I put the below code ! (instead of #svg1, I put id variable declared above)
});

To add pan zoom to svg, you can do like:

svgPanZoom("#svg1", {
         panEnabled: true,
         controlIconsEnabled: false,
         zoomEnabled: true,
         dblClickZoomEnabled: true,
         mouseWheelZoomEnabled: true,
         zoomScaleSensitivity: 0.2,
         minZoom: 0.2,
         maxZoom: 20,
         fit: true,
         contain: true,
         center: true,
         refreshRate: 'auto'
});

For new created SVG is not possible to assign svgPanZoom (throws error that it doesn't exist in DOM)

How to achieve for this ?

Upvotes: 0

Views: 559

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

I dont find any issues in

Nothing spcial creating circle dynamically on button click and adding the svg pan to it

d3.select("#b1").on("click", function () {
    var svg = d3.select("body").append("svg").attr("width", 300 + "px").attr("height", 300 + "px").attr("id", "svg1");

    var rectSelection = svg.append("circle")
        .attr("r", 50)
        .style("fill", "yellow");

    var m = svgPanZoom("#svg1", {
        panEnabled: true,
        controlIconsEnabled: false,
        zoomEnabled: true,
        dblClickZoomEnabled: true,
        mouseWheelZoomEnabled: true,
        zoomScaleSensitivity: 0.2,
        minZoom: 0.2,
        maxZoom: 3,
        fit: true,
        contain: true,
        center: true,
        refreshRate: 'auto'
    });
});

working code here

Hope this helps!

Upvotes: 1

Related Questions