This is the code for Chapter 12, Figure 5 from D3.js in Action which requires a touch interface (or emulator) to see any effect. This example uses data from d3.touches() to create SVG circles at each touch location as well as draw lines between each touch location.
Last active
March 17, 2016 02:24
-
-
Save emeeks/e57a9a1f8d27d6b84b6a to your computer and use it in GitHub Desktop.
Ch. 12, Fig. 5 - D3.js in Action
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
<html> | |
<head> | |
<title>D3 in Action Chapter 12 - Example 3</title> | |
<meta charset="utf-8" /> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
</head> | |
<style> | |
body, html { | |
width:100%; | |
height:100%; | |
} | |
#vizcontainer { | |
width:100%; | |
height:100%; | |
} | |
svg { | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
<body> | |
<div id="vizcontainer"> | |
<svg></svg> | |
</div> | |
</body> | |
<footer> | |
<script> | |
d3.select("svg").on("touchstart", touchStatus); | |
d3.select("svg").on("touchmove", touchStatus); | |
var touchColor = d3.scale.linear().domain([0, 10]).range(["pink", "darkred"]) | |
function touchStatus() { | |
d3.event.preventDefault(); | |
d3.event.stopPropagation(); | |
d = d3.touches(this); | |
d3.select("svg").selectAll("circle").data(d).enter().append("circle").attr("r", 75).style("fill", function(d, i) { | |
return touchColor(i) | |
}); | |
d3.select("svg").selectAll("circle").data(d).exit().remove(); | |
d3.select("svg").selectAll("circle").attr("cx", function(d) { | |
return d[0] | |
}).attr("cy", function(d) { | |
return d[1] | |
}); | |
var l = []; | |
if (d.length > 1) { | |
for (x in d) { | |
for (y in d) { | |
if (y != x) { | |
var lineObj = { | |
source: d[x], | |
target: d[y] | |
}; | |
l.push(lineObj); | |
} | |
} | |
} | |
d3.select("svg").selectAll("line").data(l).enter().append("line").style("stroke", "black").style("stroke-width", "3px"); | |
d3.select("svg").selectAll("line").attr("x1", function(d) { | |
return d.source[0] | |
}).attr("y1", function(d) { | |
return d.source[1] | |
}).attr("x2", function(d) { | |
return d.target[0] | |
}).attr("y2", function(d) { | |
return d.target[1] | |
}) | |
} | |
d3.select("svg").selectAll("line").data(l).exit().remove(); | |
} | |
</script> | |
</footer> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment