D3.js SVG图像边界框偏移量

时间:2016-10-11 11:27:14

标签: javascript html d3.js svg

我正在尝试使用D3.js用svg图像填充div。到目前为止,我已经能够使我的图像居中,并随着我的成长和缩小浏览器窗口而观察它。但是,当试图动态找到图像的边界框时,我只能找到画布的左上角属性和所有空间的宽度,而不仅仅是原始图像。

这是我的问题的基本模拟: http://jsfiddle.net/wnwfn/79/



d3.select("#svgEmbed").append("image")
    .attr("xlink:href","http://www.clipartkid.com/images/32/square-clip-art-black-and-white-clipart-panda-free-clipart-images-UkJ6sF-clipart.png")
    .attr("width", "100%")
    .attr("height", "100%")
    

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.12/d3.min.js"></script>
<p>
    <svg id="svgEmbed" height="100%" width="100%"    ></svg>
</p>
&#13;
&#13;
&#13;

所以我的问题是如何在这个例子中找到方形图像的左上角位置?我使用.offset(),. getBBox()进行过游戏,但我似乎无法获得我想要的值。

1 个答案:

答案 0 :(得分:0)

你的方法不起作用。通过将图像宽度/高度设置为100%,图像元素将始终位于[0,0]。如果您知道要显示图像的像素大小,可以执行以下操作:

var imgSize = 150;
var img = d3.select("#svgEmbed")
  .append("image")
  .attr("xlink:href", "http://www.clipartkid.com/images/32/square-clip-art-black-and-white-clipart-panda-free-clipart-images-UkJ6sF-clipart.png")
  .attr("x", "50%")
  .attr("width", imgSize)
  .attr("height", imgSize)
  .attr("transform", "translate(" + (-imgSize / 2) + ", 0)");

d3.select(window).on("resize", function(){
  console.log(img.node().getBBox());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<p>
  <svg id="svgEmbed" height="100%" width="100%"></svg>
</p>