How to draw a square using area in d3.js? Is it even possible to do that?
My code:
var data = [
{x: 0, y: 0},
{x: 5, y: 0},
{x: 0, y: 5},
{x: 5, y: 5},
];
var xScale = d3.scaleLinear().domain([0, 6]).range([25, 175]);
var yScale = d3.scaleLinear().domain([0,20]).range([175, 25]);
var area = d3.area()
.x(d => xScale(d.x))
.y0(yScale(0))
.y1(d => yScale(d.y));
d3.select("#demo1")
.append("path")
.attr("d", area(data))
.attr("fill", "red")
.attr("stroke", "black");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="demo1" width="200" height="200"></svg>
Thanks for help!
You can create a square using d3.area() using the following points:
var points = [
{ xpoint: 0, ypoint: 200 },
{ xpoint: 200, ypoint: 200 }
];
var points = [
{ xpoint: 0, ypoint: 200 },
{ xpoint: 200, ypoint: 200 }
];
var Gen = d3.area()
.x((p) => p.xpoint)
.y0((p) => 0)
.y1((p) => p.ypoint);
d3.select("#gfg")
.append("path")
.attr("d", Gen(points))
.attr("fill", "green")
.attr("stroke", "black");
svg { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="gfg" width="200" height="200"></svg>
For the shape in your image, try the following points:
var points = [
{ xpoint: 0, ypoint: 0 },
{ xpoint: 100, ypoint: 100 },
{ xpoint: 125, ypoint: 125 },
{ xpoint: 150, ypoint: 175 },
{ xpoint: 190, ypoint: 175 },
{ xpoint: 150, ypoint: 100 },
{ xpoint: 50, ypoint: 0 },
];
var points = [
{ xpoint: 0, ypoint: 0 },
{ xpoint: 100, ypoint: 100 },
{ xpoint: 125, ypoint: 125 },
{ xpoint: 150, ypoint: 175 },
{ xpoint: 190, ypoint: 175 },
{ xpoint: 150, ypoint: 100 },
{ xpoint: 50, ypoint: 0 },
];
var Gen = d3.area()
.x((p) => p.xpoint)
.y0((p) => 0)
.y1((p) => p.ypoint);
d3.select("#gfg")
.append("path")
.attr("d", Gen(points))
.attr("fill", "green")
.attr("stroke", "black");
svg { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="gfg" width="200" height="200"></svg>