简体   繁体   English

d3js zoom svg和axix

[英]d3js zoom svg and axix

I'm trying to draw an external svg file into a webpage using d3 and make it zoom on scroll. 我正在尝试使用d3将外部svg文件绘制到网页中并使其放大滚动。 I followed http://bl.ocks.org/mbostock/3892919 but when i add my svg file it remain fixed and doesn't zoom. 我跟着http://bl.ocks.org/mbostock/3892919但是当我添加我的svg文件时它仍然是固定的并且不会缩放。 I will draw several svg so i will have an array like this: 我将绘制几个svg所以我将有这样的数组:

var data = []
data.push({
  name: "base",
  x: 50,
  y: 50,
  width: 350,
  url: 'https://upload.wikimedia.org/wikipedia/commons/1/15/Svg.svg'
});

and draw it with a function: 并使用函数绘制它:

function add(elements, offsetX = 0, offsetY = 0) {
  for (let e of elements) {
    d3.xml(e.url, 'image/svg+xml', function(error, xml) {
      if (error) {
        console.log('error' + error)
        throw error;
      }
      var svgNode = xml.getElementsByTagName('svg')[0];
      d3.select(svgNode).attr('id', e.name)
        .attr('x', e.x + offsetX)
        .attr('y', e.y + offsetY);
      svg.node().appendChild(svgNode);
      svg.select('#' + e.name)
        .attr('width', e.width);
    });
  }
}

full jsfiddle 完整的jsfiddle

I looked around the pan & zoom examples available and this is what I found. 我查看了可用的平移和缩放示例,这是我发现的。 In the zoomed function, there should be a translate and scale on the elements appended, not just the x and y axis. zoomed功能中,应该在附加的元素上进行平移和缩放,而不仅仅是x和y轴。

So, I created a group where to append the elements: 所以,我创建了一个附加元素的组:

var elementsToScale = svg.append("g").attr("id", "elementsToScale")

And I added the last lines in the zoomed function: 我添加了zoomed功能中的最后zoomed行:

function zoomed() {
  svg.select(".x.axis").call(xAxis);
  svg.select(".y.axis").call(yAxis);
  var translate = d3.event ? d3.event.translate : "0,0"
  var scale = d3.event ? d3.event.scale : "1"
  svg.select("#elementsToScale").attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")");    
}

And then I changed the add function to append the elements to the elementsToScaleGroup : 然后我更改了add函数以将元素追加到elementsToScaleGroup

d3.xml(el.url, 'image/svg+xml', function(error, xml) {
    if (error) {
      console.log('error' + error)
      throw error;
    }
    var svgNode = xml.getElementsByTagName('svg')[0];
    d3.select(svgNode).attr('id', e.name)
      .attr('x', el.x + offsetX)
      .attr('y', el.y + offsetY);

    elementsToScale.node().appendChild(svgNode);
    elementsToScale.select('#' + el.name)
      .attr('width', el.width);
});

Here is a working fiddle . 这是一个工作小提琴

The only thing left is the tween on the elements appended on reset. 唯一剩下的就是重置时附加的元素上的补间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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