在D3中选择并移动导入的SVG文件

时间:2014-08-13 17:48:45

标签: javascript svg d3.js

我正在尝试使用d3,我一直在努力使用我用Illustrator制作的简单svg图像。

我可以将submarine.svg图像附加到我的工作文档中,但是我无法选择它并调整它的位置。

我知道我可以用另一种方式做到这一点,但我想了解有关d3的更多信息。

这是我尝试将svg放在横跨x轴的500px处。

var submarine = d3.xml("submarine.svg", "image/svg+xml", function(xml) { document.body.appendChild(xml.documentElement)
      }) d3.select(this).attr("x","500");

1 个答案:

答案 0 :(得分:1)

请参阅此示例:http://jsfiddle.net/y1ye2u8s/2/

// Define a drag behavior for the image.
var drag = d3.behavior.drag()
    .on("drag", dragmove);

// Function that is called upong dragging.
function dragmove(d) {

      var x = d3.event.x;
      var y = d3.event.y;

      // Select and move the image upon dragging.
      d3.select(this)
          .attr("transform", "translate(" + (x-200) + "," + (y-200) + ")");
}

d3.xml("https://rawgit.com/VengadoraVG/moving-to-gnulinux/master/img/tux.svg", "image/svg+xml", 

    function (xml) {

        // Add the image to the document.
        document.body.appendChild(xml.documentElement);

        // Select the svg element representing the image.
        d3.select("svg")

            // Set the svg viewport dimensions.
            .attr("width", "1000")
            .attr("height", "1000");

       // Apply the drag behavior to the image.
       d3.select("svg").select("g")
            .call(drag);    

});