block by emeeks 4507f178d23324abb1ed

Ch. 12, Fig. 3 - D3.js in Action

Full Screen

This is the code for Chapter 12, Figure 3 from D3.js in Action which requires a touch interface (or emulator) to see any effect. This example uses d3.touches() as a data source to create SVG circle elements at every touch location.

index.html

<html>
<head>
  <title>D3 in Action Chapter 12 - Example 2</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("#vizcontainer")
    .append("div").attr("id", "touchStatus")
      .append("p")
      .append("ol");
    
    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]});
      
    }
</script>
  </footer>

</html>