Skip to content

Instantly share code, notes, and snippets.

@puzzler10
Last active August 23, 2019 14:59
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 puzzler10/91a6b53d4237c97752d0e466443dad0b to your computer and use it in GitHub Desktop.
Save puzzler10/91a6b53d4237c97752d0e466443dad0b to your computer and use it in GitHub Desktop.
Simple Zoom Example v4 II

This is an simple example of adding zoom to your graph.

Click here to read a more detailed explanation on how zoom works.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<svg width="800" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//create some circles at random points on the screen
//create 50 circles of radius 20
//specify centre points randomly through the map function
var radius = 20;
var circle_data = d3.range(50).map(function() {
return{
x : Math.round(Math.random() * (width - radius*2 ) + radius),
y : Math.round(Math.random() * (height - radius*2 ) + radius)
};
});
//draw the circles on the page
var circles = svg.append("g")
.attr("class", "circles")
.selectAll("circle")
.data(circle_data)
.enter()
.append("circle")
//same as .attr("cx", function(d) {return(d.x)})
.attr("cx", (d) => d.x)
//same as .attr("cy", function(d) {return(d.y)})
.attr("cy", (d) => d.y)
.attr("r", radius)
.attr("fill", "blue");
//create zoom handler
var zoom_handler = d3.zoom()
.on("zoom", zoom_actions);
//specify what to do when zoom event listener is triggered
function zoom_actions(){
circles.attr("transform", d3.event.transform);
}
//add zoom behaviour to the svg element
//same as svg.call(zoom_handler);
zoom_handler(svg);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment