我无法添加平移和缩放D3.js图表的功能。我尝试了多种方法,但似乎无法弄清楚。
理论上,当用户滚动或使用鼠标在图形片段之间拖动时,我想要缩放效果。当用户拖动到这些区域之外时,使用平移效果。
有关如何执行此操作的任何想法或示例?我现在所处位置的代码如下。
谢谢,
addPanAndZoom: function(chart, chartType, chartMargin, numXLabels, svg, redraw) {
// graph dom elements
var rect = svg.select('rect'),
paths = svg.select('path');
// Chart dimensions
var width = Number(rect.attr("width")),
height = Number(rect.attr("height"));
var xDomain = chart.xDomain;
var numXTicks = numXLabels - 1,
numYTicks = 10;
var scaleExtent = 10;
var x = d3.scale.linear().rangeRound([0, width]).domain([0, numXTicks]),
y = d3.scale.linear().rangeRound([0, height]).domain([height, 0]);
var make_x_axis = function () {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues(numXTicks);
};
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues(numXTicks);
var make_y_axis = function () {
return d3.svg.axis()
.scale(y)
.orient("left")
.tickValues(numYTicks);
};
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickValues(numYTicks);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, scaleExtent])
.on("zoom", zoomed);
svg.call(zoom);
function zoomed() {
console.log('zoomed');
var translate = zoom.translate(),
scale = zoom.scale();
var xTranslate = translate[0],
yTranslate = translate[1];
// set min and max axis values
var totalWidth = width * scale;
var min = Math.max(0, numXTicks * (xTranslate / totalWidth)),
max = Math.min(numXTicks, numXTicks * ((-xTranslate + width) / totalWidth));
// minor tweak -- snap min/max to end if close enough
if (min / numXTicks < 0.05) min = 0;
if (max / numXTicks > 0.95) max = numXTicks;
// set the domain for the x axis
xDomain([min, max]);
// redraw chart
redraw();
}
}