Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


SVG Boilerplate Drag Zoom D3js

31 Aug 2020 » web

d3jsv6

https://observablehq.com/@d3/drag-zoom

<html>
<head>
<script type="text/javascript" src="https://unpkg.com/d3@6.1.1/dist/d3.min.js"></script>
</head>
<body>


<script>

width = document.body.scrollWidth - 20
height = document.body.scrollHeight - 20
var svg = d3.select("body").append("svg")
            .attr("width", `${width}px`)
            .attr("height", `${height}px`)
var g = svg.append("g")

d3.xml("<your svg>").then((rs) => {
    console.log(rs)
    var svgNode = rs.getElementsByTagName("svg")[0];
    g.node().appendChild(svgNode)
})

  svg.call(d3.zoom()
      .extent([[0, 0], [width, height]])
      .scaleExtent([-5, 20])
      .on("zoom", zoomed));

  function dragstarted() {
    d3.select(this).raise();
    g.attr("cursor", "grabbing");
  }

  function dragged(event, d) {
    d3.select(this).attr("cx", d.x = event.x).attr("cy", d.y = event.y);
  }

  function dragended() {
    g.attr("cursor", "grab");
  }

  function zoomed({transform}) {
    g.attr("transform", transform);
  }

</script>
</body>
</html>