From c74a1d408bf036c7469b48f007f5b97c04340fd2 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Wed, 24 Aug 2016 00:30:14 -0400 Subject: [PATCH] inverting x/y values after transform --- D3.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/D3.md b/D3.md index a94962f..07a3fcd 100644 --- a/D3.md +++ b/D3.md @@ -246,7 +246,9 @@ You can use the xScale.invert and yScale.invert to get data from d3.event.x and //previously defined: d3.select('svg').append('g').attr('id', 'x-axis').attr('transform', 'translate(0,' + HEIGHT + ')').call(xAxis); //previously defined: d3.select('svg').append('g').attr('id', 'y-axis').call(yAxis); //y axis is good as it is var zoomCallback = function(){ - d3.select('#points').attr("transform", d3.event.transform); + lastTransform = d3.event.transform; //save the transform for later inversion with clicks + d3.select('#points').attr("transform", d3.event.transform); //apply transform to g element containing circles + //recalculate the axes d3.select('#x-axis').call(xAxis.scale(d3.event.transform.rescaleX(xScale))); d3.select('#y-axis').call(yAxis.scale(d3.event.transform.rescaleY(yScale))); } @@ -254,6 +256,23 @@ var zoom = d3.zoom().on('zoom', zoomCallback); d3.select('svg').call(zoom); ``` +If you need to recalculate new mouse position after transform, use the last saved event transform's invert methods + +```javascript +var lastTransform = null; +d3.select('svg').on('click', function(d){ + + //d3.event contains data for click event + var x = d3.event.offsetX; //use offset to get point within svg container + var y = d3.event.offsetY; + + if(lastTransform !== null){ + x = lastTransform.invertX(d3.event.offsetX); //use offset to get point within svg container + y = lastTransform.invertY(d3.event.offsetY); + } + //... +``` + ## Basic Layouts - https://github.com/d3/d3/wiki/Plugins - http://c3js.org/