将svg pan zoom添加到动态创建的带有D3js的svg中

时间:2015-11-10 09:50:53

标签: javascript d3.js svg

对于平移和缩放,我使用this库。

因此,当我右键单击时,我使用D3js库创建一个新的SVG元素,如:

$("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)
});

要将平移缩放添加到svg,您可以这样做:

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'
});

对于新创建的SVG,无法分配svgPanZoom(抛出DOM中不存在的错误)

如何实现这个目标?

1 个答案:

答案 0 :(得分:0)

我在

中找不到任何问题

在点击按钮并向其添加svg平底锅时,没有动态创建圆圈

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'
    });
});

工作代码here

希望这有帮助!