简体   繁体   English

D3缩放jquery按钮单击

[英]D3 zoom on jquery button click

I'm trying to implement a simple d3 svg zoom functionality. 我正在尝试实现一个简单的d3 svg缩放功能。 On double clicking the rectangle the zoom functionality is working fine. 在双击矩形时,缩放功能正常工作。

Now i'm trying to implement the same functionality on a jquery button click function. 现在我正在尝试在jquery按钮单击功能上实现相同的功能。 But i'm getting following error in the console. 但我在控制台中遇到以下错误。

Uncaught TypeError: Cannot read property 'translate' of null Following is my code. Uncaught TypeError: Cannot read property 'translate' of null以下是我的代码。

 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> 

The functionality is not working. 功能无效。 What am i doing wrong or is it possible to implement such functionality ? 我做错了什么或者是否可以实现这样的功能?

At the time of the click you don't have d3.event set, because no events is comming from d3, hence you have to specify yourself the scale / translate parameters 在单击时你没有设置d3.event,因为没有事件来自d3,因此你必须自己指定scale / translate参数

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

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

D3 has its own event generating mechanism on double click. D3双击时有自己的事件生成机制。 As you have the click handler on an element that is not handled by D3, you don't have a d3.event . 由于您在D3未处理的元素上有click处理程序,因此您没有d3.event

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

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

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