[英]How to add zooming to chart D3 JS
I have this DEMO and I'm trying to add zooming functionality with the following code as in this example : 我有这个DEMO ,我正尝试使用以下示例中的代码添加缩放功能:
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var svg = d3.select("#vis").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
function zoomed() {
svg.append("g").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
But my chart doesn't zoom. 但是我的图表无法缩放。
Any ideas on how to solve this? 关于如何解决这个问题的任何想法?
Thanks! 谢谢!
The problem is that svg doesn't capture mouse events on a group unless there is a visual element present. 问题在于,除非存在视觉元素,否则svg不会捕获组中的鼠标事件。 You can see this for yourself by listening for a simple
click
event on the group (instead of call(zoom)
). 您可以通过侦听组中的简单
click
事件(而不是call(zoom)
)来亲自查看。 The click
event will never be fired. click
事件将永远不会被触发。
In the d3 example, Mike Bostock adds a rect that is the width and height of the svg to work around this, and you can do something similar. 在d3示例中,Mike Bostock添加了一个矩形,即svg的宽度和高度来解决此问题,您可以执行类似的操作。
Here is a zoomable Plunker with that placeholder rect: http://plnkr.co/edit/N3WXCEkYpNgMflWmG8e4?p=preview 这是带有该占位符rect的可缩放Plunker: http ://plnkr.co/edit/N3WXCEkYpNgMflWmG8e4?p=preview
Here is the relevant code: 以下是相关代码:
var svg = d3.select("#vis").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.classed('transform-target', true)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
svg.append("rect")
.style('fill', 'transparent')
.attr("width", width)
.attr("height", height);
You should be able to zoom in and out using doubleclick or scroll. 您应该能够使用双击或滚动来放大和缩小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.