Last active
October 9, 2017 12:14
-
-
Save bfunc/e8c5649f1a3233b4141b36f6ffdff79c to your computer and use it in GitHub Desktop.
d3 v4 - detect click coordinates in zoomed area
This file contains 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> | |
<script src="https://d3js.org/d3.v4.js"></script> | |
<style> | |
body {margin: 0 } | |
svg { background-color: #86B2EB; } | |
svg circle.old { fill: green; } | |
svg circle.new { fill: blue; } | |
</style> | |
</head> | |
<body> | |
<svg width="960" height="500"></svg> | |
<h4>Zoom with mousewheel and click to add circle</h4> | |
<script> | |
let svg = d3.select('svg'), | |
container = svg.append('g'), | |
data = [ | |
{ x: 50, y: 110, id: 100 }, | |
{ x: 100, y: 100, id: 101 }, | |
{ x: 650, y: 410, id: 102 } | |
]; | |
function init() { | |
let zoom = d3.zoom() | |
.scaleExtent([0.25, 2.25]) | |
.on("zoom", () => { | |
container.attr("transform", d3.event.transform); | |
}); | |
svg.call(zoom) | |
.on("dblclick.zoom", null) | |
svg.on('click', d => { | |
let x = d3.event.x; | |
let y = d3.event.y; | |
// TODO - get new x,y coords affected by current zoom ration | |
// x = zoom ... | |
// y = zoom ... | |
data.push({ x, y, id: Math.random() }); | |
redraw(); | |
}); | |
} | |
function redraw() { | |
let grp = container.selectAll('circle') | |
.data(data, d => d.id) | |
.attr('class', 'old') | |
grp.exit().remove(); // exit > remove > g | |
let grpEnter = grp.enter() | |
let group = grpEnter | |
group.append('circle') | |
.attr('class', 'new') | |
.attr('r', 15) | |
.attr('cx', d => d.x).attr('cy', d => d.y) | |
grp = grpEnter.merge(grp); | |
} | |
init(); | |
redraw(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment