Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active April 29, 2020 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save d3indepth/12af91c5f58bc9eedf96f7c0a9f5622f to your computer and use it in GitHub Desktop.
Save d3indepth/12af91c5f58bc9eedf96f7c0a9f5622f to your computer and use it in GitHub Desktop.
Scale inversion
license: gpl-3.0
height: 100
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Scale inversion</title>
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
}
rect {
fill: #ccc;
cursor: pointer;
}
.info {
margin-left: 20px;
}
</style>
<body>
<svg width="700" height="80">
<g transform="translate(20, 10)">
<g class="axis" transform="translate(0, 40)"></g>
<rect class="click-area"></rect>
</g>
</svg>
<div class="info">Click on the grey band</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var width = 600;
var linearScale = d3.scaleLinear()
.domain([-50, 50])
.range([0, width])
.nice();
var clickArea = d3.select('.click-area').node();
function doClick() {
var pos = d3.mouse(clickArea);
var xPos = pos[0];
var value = linearScale.invert(xPos);
d3.select('.info')
.text('You clicked ' + value.toFixed(2));
}
// Construct axis
var axis = d3.axisBottom(linearScale);
d3.select('.axis')
.call(axis);
// Update click area size
d3.select('.click-area')
.attr('width', width)
.attr('height', 40)
.on('click', doClick);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment