Fill D3 arrow with colors

Tags: d3.js, javascript, svg

I managed to plot an arrow with D3 that changes direction and size dynamically. Now, I would like to fill the encapsulated area with a color. However, I plot the arrow outline with a succession of lines, so I am not sure how to tell D3 that this area is closed and ready to fill?

for (let i = 0; i < ARROW_SHAPE.length - 1; i++){

const x1: number = ARROW_SHAPE[i] * Math.cos(angle) - ARROW_SHAPE[i] * Math.sin(angle);
const y1: number = ARROW_SHAPE[i] * Math.sin(angle) + ARROW_SHAPE[i] * Math.cos(angle);

const x2: number = ARROW_SHAPE[i + 1] * Math.cos(angle) - ARROW_SHAPE[i + 1] * Math.sin(angle);
const y2: number = ARROW_SHAPE[i + 1] * Math.sin(angle) + ARROW_SHAPE[i + 1] * Math.cos(angle);

this.g.append('line')
.attr('stroke', color)
.attr('stroke-width', 4)
.attr('x1', x1 * size)
.attr('y1', y1 * size)
.attr('x2', x2 * size)
.attr('y2', y2 * size);
}

How shall I adjust my dummy code to create a polygon out of my lines and allow it to be filled?

Don’t create your arrow from a series of individual lines. Create a <polygon> or a <path> instead. A polygon is easiest.

const arrow = [];
for (let i = 0; i < ARROW_SHAPE.length - 1; i++){
arrow.push( ARROW_SHAPE[i] * Math.cos(angle) - ARROW_SHAPE[i] * Math.sin(angle))
arrow.push(ARROW_SHAPE[i] * Math.sin(angle) + ARROW_SHAPE[i] * Math.cos(angle));
}

this.g.append('polygon')
.attr('fill', color)
.attr('stroke-width', 4)
.attr('points', arrow.join(','))

Source: stackoverflow