Skip to content

Instantly share code, notes, and snippets.

@pwldp
Forked from arunkjn/index.html
Created March 22, 2017 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwldp/39a4fb321e0f81b4b4e37bb8ef0020e3 to your computer and use it in GitHub Desktop.
Save pwldp/39a4fb321e0f81b4b4e37bb8ef0020e3 to your computer and use it in GitHub Desktop.
Multiple polygons with d3.js
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 700,
svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height),
scaleX = d3.scale.linear()
.domain([-30,30]) //Give appropriate range in the scale
.range([0,width]),
scaleY = d3.scale.linear()
.domain([0,50]) //Give appropriate range in the scale
.range([height,0]);
d3.json("polygons.json", function(data) {
svg.selectAll("polygon")
.data(data.Polygons)
.enter().append("polygon")
.attr("points",function(d) {
return d.points.map(function(d) { return [scaleX(d.x),scaleY(d.y)].join(","); }).join(" ");})
.attr("stroke","black")
.attr("stroke-width",2);
});
</script>
{
"Polygons": [{
"name": "polygon 1",
"points":[
{"x":0.0, "y":25.0},
{"x":8.5,"y":23.4},
{"x":13.0,"y":21.0},
{"x":19.0,"y":15.5}
]
},
{
"name": "polygon 2",
"points":[
{"x":0.0, "y":50.0},
{"x":15.5,"y":23.4},
{"x":18.0,"y":30.0},
{"x":20.0,"y":16.5}
]
},
{
"name": "polygon 3",
"points":[
{"x":10, "y":30.0},
{"x":19,"y":15.4},
{"x":18.4,"y":46.0},
{"x":15.8,"y":19.5}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment