Created
November 7, 2017 14:26
-
-
Save valex/1f044d548291007b0b8fa0a1bc50df56 to your computer and use it in GitHub Desktop.
Pan and zoom, d3.js version 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script src="http://d3js.org/d3.v4.min.js"></script> | |
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script> | |
<script> | |
var width = 450, height = 450, radius = 50; | |
var zoomBehavior = d3.zoom() | |
.scaleExtent([0.1, 10]) | |
.on('zoom', onZoom); | |
var svg = d3.select('body') | |
.append('svg') | |
.attrs({ | |
width: width, | |
height: height | |
}) | |
.call(zoomBehavior) | |
.append('g'); | |
var data = [ | |
[width / 2 - radius, height / 2 - radius], | |
[width / 2 - radius, height / 2 + radius], | |
[width / 2 + radius, height / 2 - radius], | |
[width / 2 + radius, height / 2 + radius]]; | |
var colors = d3.schemeCategory10; | |
var circles = svg.selectAll('circle') | |
.data(data) | |
.enter() | |
.append('circle') | |
.attrs({ | |
r: radius, | |
fill: function (d,i) { return colors[i]; }, | |
transform: function (d) { return 'translate(' + d + ')' } | |
}); | |
var dragBehavior = d3.drag() | |
.on('drag', onDrag) | |
.on('start', function () { | |
d3.event.sourceEvent.stopPropagation(); | |
}); | |
// Applies this drag behavior to the specified selection. | |
circles.call(dragBehavior); | |
function onDrag(d) { | |
var x = d3.event.x, | |
y = d3.event.y; | |
if ((x >= radius) && (x <= width - radius) && | |
(y >= radius) && (y <= height - radius)) { | |
d3.select(this) | |
.attr('transform', function () { | |
return 'translate(' + x + ', ' + y + ')'; | |
}); | |
} | |
} | |
function onZoom() { | |
svg.attr('transform', 'translate(' + d3.event.transform.x +', '+ d3.event.transform.y + ')' + | |
'scale(' + d3.event.transform.k + ')'); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment