下面是我的JavaScript代码,它绘制了data
数组中定义的给定数据的散点图。当我在散点图上执行缩放并使用mousedown
事件拖动绘图时,散点图从中心移动。
我想知道如何在缩放散点图后返回其原始位置修改我的代码?在当前设置中,我使用reset
按钮控制此行为,但我想知道如何自动执行此操作。
JSFiddle是here,d3.js代码粘贴在下面。
var data = [{
centrality: 12,
density: 15
}, {
centrality: 14,
density: 9
}, {
centrality: 10,
density: 6
}, {
centrality: 16,
density: 7
}, {
centrality: 8,
density: 5
}]
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 500 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Set the range for x axis
var x = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.centrality;
})])
.range([0, width]);
// Set the range for y axis
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.density;
})])
.range([height, 0]);
// Define mean of x axis
var xMean = d3.mean(data, function(d) {
return d.centrality;
})
// Define mean of y axis
var yMean = d3.mean(data, function(d) {
return d.density;
})
// Define zoom function event listener
function zoomFunction() {
var transform = d3.zoomTransform(this);
d3.select("#map_g")
.attr("transform", "translate(" + transform.x + "," + transform.y + ") scale(" + transform.k + ")");
}
// Define zoom behavior
var zoom = d3.zoom()
.scaleExtent([1, 5])
.on("zoom", zoomFunction)
var chart = d3.select('#main')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
.attr("id", "map_g")
.call(zoom)
.call(zoom.transform, d3.zoomIdentity)
.on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null)
.on('mousedown.drag', null);
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// Draw the x axis
var xAxis = d3.axisBottom()
.scale(x)
//.orient('center')
.tickSizeOuter(0)
.tickValues([]);
main.append('g')
.attr('transform', 'translate(0,' + y(yMean) + ')')
.attr('class', 'main axis date')
.call(xAxis);
// Draw the y axis
var yAxis = d3.axisLeft()
.scale(y)
//.orient('right')
.tickSizeOuter(0)
.tickValues([]);
main.append('g')
.attr('transform', 'translate(' + x(xMean) + ',0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
var circle = g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function(d, i) {
return x(d.centrality);
})
.attr("cy", function(d) {
return y(d.density);
})
.attr("r", 5)
.attr("fill", "black")
// Reset function
function resetted() {
chart.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}
// Reset button
d3.select("button")
.on("click", resetted);