I have these polygons coming from variables and being stored in poly, so polygons are being displayed all over the webpage but I want all the polygons to be displayed on a single image, so how should I write the code here using D3 to display all the polygons on that specific image only.
Please help, I have been trying these for the last few days but couldn't find a proper solution.
...
var vis = d3.select("body").append("svg")
.attr("width", 1000)
.attr("height", 667),
poly = [{"x":x1, "y":y1},
{"x":x2,"y":y2},
{"x":x3,"y":y3},
{"x":x4,"y":y4}];
vis.selectAll("polygon")
.data([poly])
.enter().append("polygon")
.attr("points",function(d) {
return d.map(function(d) { return [d.x,d.y].join(","); }).join(" ");})
.attr("stroke","red")
.attr("fill","none"); }
...
CodePudding user response:
Use the viewBox property of the svg. Viewbox should match the margins of the image and it should expand to the height and width of the image. Once viewBox is set, change the css for overlay of the svg over image. I have changed the code below for a sample image
var vis = d3.select("#overlay").append("svg")
.attr("width", 200)
.attr("height", 300)
.attr("viewBox","-10 0 200 200");
var poly = [{"x":20, "y":50},
{"x":30,"y":0},
{"x":40,"y":10},
{"x":50,"y":60}];
vis.selectAll("polygon")
.data([poly])
.enter().append("polygon")
.attr("points",function(d) {
return d.map(function(d) { return [d.x,d.y].join(","); }).join(" ");})
.attr("stroke","red")
.attr("fill","none");
svg{
z-index:1000;
}
.img-overlay {
position: relative;
display: inline-block; /* <= shrinks container to image size */
transition: transform 150ms ease-in-out;
margin-left:10px;
}
.img-overlay svg {
position: absolute;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<body>
<div id="overlay" >
<img id="vv" src="https://via.placeholder.com/200" ></img>
</div>
</body>
CodePudding user response:
What exactly do you mean by polygons being displayed all over the webpage and wanting them displayed on a specific image?