block by jeremycflin 833198d504063625b5ec0ca373bb7b61

Canvas+SVG hover stroke effect

Full Screen

forked from LuisSevillano‘s block: Canvas+SVG hover stroke effect

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
  path {
    stroke-linecap: round;
    stroke-linejoin: round;
  }
  .municipalities {
    visibility: hidden;
    stroke: black;
    stroke-width:2;
    fill:none;
    pointer-events: all;
  }
  .municipalities.active {
    visibility: visible;
  }
  svg,
  canvas {
    position: absolute;
    top: 0;
    left: 0;
  }
  </style>
</head>
<body>
  <!DOCTYPE html>
  <canvas width="960" height="600"></canvas>
  <svg width="960" height="600"></svg>

  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script src="https://d3js.org/topojson.v2.min.js"></script>
  <script src="https://unpkg.com/d3-composite-projections@1.0.2"></script>
  <script>

  var context = d3.select("canvas").node().getContext("2d"),

  svg = d3.select("svg"),
  width = 960,
  height = 600,
  path = d3.geoPath(),
  canvasPath = d3.geoPath().context(context);

  d3.queue()
  .defer(d3.json, 'https://gist.githubusercontent.com/LuisSevillano/acce972dd718af898b2c2875bc4e4167/raw/8813c93f7b66366e6bd2f9b1937be0cac24ff59b/municipalities.json')
  .defer(d3.csv, 'https://gist.githubusercontent.com/LuisSevillano/acce972dd718af898b2c2875bc4e4167/raw/8813c93f7b66366e6bd2f9b1937be0cac24ff59b/municipalities_population.csv')
  .await(function(error, es, population) {

    // loop through the csv to create a new object accesible by ids
    var data = [];
    population.forEach(function(d){
      data[d.id] = {"id":d.id,"rate":+d.rate};
    });
    color = d3.scaleThreshold()
    .range(['#d0e4f1','#c0d6e9','#afc7e1','#9fb8da','#8eaad2','#7d9ccb','#6c90c3','#5982bc','#4575b4'])
    .domain([5, 9, 19, 49, 74, 124, 249, 499, 1000]);

    features = topojson.feature(es, es.objects.municipalities).features;

    for (var i = 0; i < features.length; i++) {

      if (data[features[i].id]) {

        context.fillStyle = color(data[features[i].id].rate);
        context.beginPath()
        canvasPath(features[i])
        context.fill()
      }
    }

    svg.selectAll(".municipalities")
    .data(features)
    .enter()
    .append("path")
    .attr('d', path)
    .attr('class', 'municipalities')
    .on("mouseover", function(d){
      d3.select(this).classed('active', true)

    })
    .on("mouseout", function(d){
      d3.select(this).classed('active', false)
    });

    // border
    context.beginPath()
    canvasPath(topojson.feature(es, es.objects.nation))
    context.strokeStyle = "rgb(100, 100, 100)";
    context.stroke()

  });



  </script>

</body>
</html>