Josh
Josh

Reputation: 338

How do you fill specific countries using d3.geo with canvas?

I created my own pre-projected topojson file, and I am trying to change the fillstyle of a specific country in my canvas. http://bl.ocks.org/anonymous/fea6cfde1184e2f10de8 is my code/example. I tried to catch the specific country code and set a fill for that country (Germany in this case). However, it fills a bunch of other countries in for some reason as well. I suspected it might be a shared borders issue, but some countries that do not share a border get filled as well.

Also interesting is that if I do not render the borders for the other countries as in http://bl.ocks.org/anonymous/3256fe09efaa8d2ebc96 the fill works, but obviously all the borders disappear. Am I simply not understanding how canvas fills work? Is there a different way to highlight a specific country? It has occurred to me that I can use a mask to fill in a specific country, but that seems like an awfully roundabout way to do it.

Note, I am aware that it is way simpler to do using SVG/CSS, but I would really like to get it working in canvas.

Upvotes: 2

Views: 1603

Answers (1)

Mark
Mark

Reputation: 108537

As in this example, you need to draw all the borders first, then just fill the region you want:

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

    if (geoJson.features[i].id == "DEU") {
      isDEU = geoJson.features[i];
    }

    context.save();
    canvasPath(geoJson.features[i]);
    context.stroke();
    context.restore();
  }

  context.fillStyle = "#f00"
  context.beginPath();
  canvasPath(isDEU);
  context.fill();

Example here.

Upvotes: 2

Related Questions