D3 increase when jquery button is pressed

I am trying to implement simple d3 svg zoom functionality. Double-clicking on the rectangle scaling functionality works fine.

Now I'm trying to implement the same functionality when I click the jquery button. But I get the following error in the console.

Uncaught TypeError: Cannot read property 'translate' of null Below is my code.

var zoom = d3.behavior.zoom()
  .scaleExtent([1, 10])
  .on("zoom", zoomed);

var vis = d3.select("#svg-canvas").append("svg")
  .attr("width", "550")
  .attr("height", "200")
  .append("g")
  .attr("class", "svg-container")
  .attr("transform", "translate(10,10)")
  .call(zoom);

vis.append("rect")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 100)
  .attr("height", 40)
  .style("fill", "#444");

function zoomed() {
  d3.select(".svg-container").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

$(document).ready(function() {
  $("#zoom").click(function() {
    zoomed();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="svg-canvas">

</div>

<button id="zoom">
  Zoom
</button>
Run codeHide result

Functionality does not work. What am I doing wrong or is it possible to implement such functions?

+4
source share
2 answers

At the time of the click, you do not have the d3.event set, because no events occur from d3, so you need to specify the scaling / translation parameters

function zoomClicked(translate, scale) {
    d3.select(".svg-container").attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}

 $(document).ready(function() {
     $("#zoom").click(function() {
         zoomClicked(4, 4);
     });
 });
+4
source

D3 . , D3, d3.event.

  d3.select(".svg-container")
    .attr("transform", scale(2)");
+1

Source: https://habr.com/ru/post/1628459/


All Articles