简体   繁体   中英

Fill D3 arrow with colors

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][0] * Math.cos(angle) - ARROW_SHAPE[i][1] * Math.sin(angle);
      const y1: number = ARROW_SHAPE[i][0] * Math.sin(angle) + ARROW_SHAPE[i][1] * Math.cos(angle);

      const x2: number = ARROW_SHAPE[i + 1][0] * Math.cos(angle) - ARROW_SHAPE[i + 1][1] * Math.sin(angle);
      const y2: number = ARROW_SHAPE[i + 1][0] * Math.sin(angle) + ARROW_SHAPE[i + 1][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][0] * Math.cos(angle) - ARROW_SHAPE[i][1] * Math.sin(angle))
  arrow.push(ARROW_SHAPE[i][0] * Math.sin(angle) + ARROW_SHAPE[i][1] * Math.cos(angle));
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM