toolkit/javascript/d3/examples/contour/contour.html
author Nicolas Sauret <nicolas.sauret@iri.centrepompidou.fr>
Fri, 18 Apr 2014 14:31:58 +0200
changeset 51 79833eaa394a
parent 47 c0b4a8b5a012
permissions -rw-r--r--
set up second level for navigation

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Contour</title>
    <script type="text/javascript" src="../../d3.js"></script>
    <script type="text/javascript" src="../../d3.geom.js"></script>
    <style type="text/css">
svg {
  border: solid 1px #aaa;
}
path {
  stroke: red;
  stroke-width: 2px;
  fill: none;
}
rect {
  fill: lightsteelblue;
  stroke: #eee;
  stroke-width: 2px;
}
rect.d1 {
  fill: steelblue;
}
rect.d2 {
  fill: darkblue;
}
    </style>
  </head>
  <body>
    <script type="text/javascript">

function grid0(x,y) {
  if (x < 0 || y < 0 || x >= dw || y >= dh) return 0;
  return data[y][x];
}
function grid1(x,y) {
  if (x < 0 || y < 0 || x >= dw || y >= dh) return 0;
  return data[y][x]==1;
}
function grid2(x,y) {
  if (x < 0 || y < 0 || x >= dw || y >= dh) return 0;
  return data[y][x]==2;
}
	
var data = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 2, 2, 2, 0, 0, 0, 0],
            [0, 0, 0, 2, 2, 2, 2, 0, 0, 0],
            [0, 0, 2, 2, 2, 2, 2, 2, 0, 0],
            [0, 0, 2, 2, 2, 2, 2, 2, 2, 0],
            [0, 0, 2, 1, 0, 0, 2, 2, 2, 0],
            [0, 0, 1, 1, 0, 0, 2, 2, 2, 0],
            [0, 0, 0, 0, 1, 1, 2, 2, 0, 0],
            [0, 0, 0, 0, 1, 2, 2, 2, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
    fn = [grid0, grid1, grid2],
    dw = data[0].length,
    dh = data.length;
    sz = 30,
    grid = grid0;

function translateY(d, i) { return "translate(0,"+(i*sz)+")"; }
function translateX(d, i) { return "translate("+(i*sz)+",0)"; }
function scale(p) { return [p[0]*sz, p[1]*sz]; }

var svg = d3.select("body")
 .append("svg:svg")
  .attr("width", dw*sz)
  .attr("height", dh*sz);

var g = svg.selectAll("g")
  .data(data)
 .enter().append("svg:g")
  .attr("transform", translateY);

g.selectAll("rect")
  .data(function(d) { return d; })
 .enter().append("svg:rect")
  .attr("transform", translateX)
  .attr("width", sz)
  .attr("height", sz)
  .attr("class", function(d) { return "d"+d; })
  .on("mouseover", mouseover);

contour(grid);

function contour(grid, start) {
  svg.selectAll("path")
    .data([d3.geom.contour(grid, start).map(scale)])
    .attr("d", function(d) { return "M" + d.join("L") + "Z"; })
   .enter().append("svg:path")
    .attr("d", function(d) { return "M" + d.join("L") + "Z"; });
}

function mouseover(d,i) {
  var s = undefined;
  grid = fn[d];
  if (d > 0) {
	// map mouse to grid coords, then find left edge
    var p = d3.svg.mouse(svg[0][0]);
    s = [Math.floor(p[0]/sz), Math.floor(p[1]/sz)];
    while (grid(s[0]-1,s[1])) s[0]--;
  }
  contour(grid, s);
}
    </script>
  </body>
</html>