Built with blockbuilder.org
forked from Igathi's block: MB zoom circles in and out
xxxxxxxxxx
<meta charset="utf-8">
<style>
.background {
fill: none;
pointer-events: all;
}
.feature {
fill: #ccc;
cursor: pointer;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script>
var active = d3.select(null);
var objh = 20;
var width = window.innerWidth;
var height = window.innerHeight;
var jsonCircles = [
{ "x": 50, "y": 50, "radius": 20, "color" : "limegreen" },
{ "x": 100, "y": 50, "radius": 20, "color" : "purple"},
{ "x": 150, "y": 50, "radius": 20, "color" : "orangered"},
{ "x": 200, "y": 50, "radius": 20, "color" : "skyblue"}
];
var zoom = d3.zoom()
.on("zoom", zoomed);
var initialTransform = d3.zoomIdentity
.translate(0,0)
.scale(1.0);
var svg = d3.select("body").append("svg")
svg.attr("width", width)
.attr("height", height)
.on("click", stopped, true);
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.style("fill", "white")
.style("stroke", "black")
.on("click", reset);
var g = svg.append("g");
svg
.call(zoom) // delete this line to disable free zooming
.call(zoom.transform, initialTransform);
var circles = g.selectAll("circle")
.data(jsonCircles)
.enter()
.append("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", function (d) { return d.radius;})
.style("fill", function(d) { return d.color;})
.attr("class", "feature")
.on("click", clicked);;
function clicked(d) {
if (active.node() === this) return reset();
active.classed("active", false);
active = d3.select(this).classed("active", true);
dx = d.radius
dy = d.radius
x = d.x
y = d.y
scale = Math.max(1, Math.min(height/objh/2, 0.9 / Math.max(dx / width, dy / height))),
translate = [width / 2 - scale * x, height / 2 - scale * y];
console.log("width");
var transform = d3.zoomIdentity
.translate(translate[0], translate[1])
.scale(scale);
svg.transition()
.duration(750)
.call(zoom.transform, transform);
}
function reset() {
active.classed("active", false);
active = d3.select(null);
svg.transition()
.duration(750)
.call(zoom.transform, initialTransform);
}
function zoomed() {
var transform = d3.event.transform;
g.style("stroke-width", 1.5 / transform.k + "px");
g.attr("transform", transform);
}
// If the drag behavior prevents the default click,
// also stop propagation so we don’t click-to-zoom.
function stopped() {
if (d3.event.defaultPrevented) d3.event.stopPropagation();
}
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/topojson.v1.min.js