Skip to content

Instantly share code, notes, and snippets.

@arunkjn
Last active July 31, 2020 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arunkjn/5042953 to your computer and use it in GitHub Desktop.
Save arunkjn/5042953 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>
<body>
<svg width="960" height="600"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 700;
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
var scaleX = d3.scale.linear()
.domain([-30,30]) //Give appropriate range in the scale
.range([0,width]);
var 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>
</body>
</html>
{
"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}
]
}
]
}
@dung1004
Copy link

how to show points and circle for each polygon ???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment