javascript - D3.js map with HTML5 canvas not showing -
i trying understand how create minimalistic example of country map using d3.js , html5 canvas. managed implement following code,
<html> <head> <title></title> </head> <body> </body> <script src="http://d3js.org/d3.v3.min.js"></script> <script src="http://d3js.org/topojson.v1.min.js"></script> <script type="text/javascript"> // drawing map in canvas var width = 960, height = 500; var canvas = d3.select("body").append("canvas") .attr("width", width) .attr("height",height); var context = canvas.node().getcontext("2d"); var projection = d3.geo.mercator(); var path = d3.geo.path() .projection(projection) .context(context); d3.json("tunisia.json", function(error, topology) { canvas .datum(topojson.object(topology, topology.objects.governorates)) .transition(); }); </script> </html> but, no results have shown in browser , no error received in console, please check. also, there minimalistic example of map canvas in d3.js
you aren't drawing inside canvas, that's why fails.

the following code work , give result in image, , can play @ this jsbin:
<html> <head> <title></title> </head> <body> </body> <script src="http://d3js.org/d3.v3.min.js"></script> <script src="http://d3js.org/topojson.v0.min.js"></script> <script type="text/javascript"> // drawing map in canvas var width = 960, height = 500; var canvas = d3.select("body").append("canvas") .attr("width", width) .attr("height",height); var context = canvas.node().getcontext("2d"); var projection = d3.geo.mercator(); var path = d3.geo.path() .projection(projection) .context(context); d3.json("https://cdn.rawgit.com/mbostock/4090846/raw/8a7f176072d508218e120773943b595c998991be/world-50m.json", function(error, data) { var land = topojson.object(data, data.objects.land); context.strokestyle = '#000000'; context.fillstyle = '#aaaaaa'; context.beginpath(); path(land); context.fill(); }); </script> </html> let's see how work:
- the part changes after loading json
- i've changed tunisia.json file one, since don't have file. if it's correct json, file should work, although you'll see tunisia quite small. change this, change scale property @ projection object.
- the variable land has polygons topojson file
- context object used draw elements in canvas. has many functions, draw lines, erase, etc. you have theme here.
- then set line color black , fill color grey using strokestyle , fillstyle. when call function point, values used
- now path initiated method beginpath(), following operations add properties path
- the next order draws everything:
- you added context path definition, data pass path added context. since land variable has polygons, polygons drawn.
- the fill method fills polygons defined color. if don't call it, nothing drawn
Comments
Post a Comment