0

我正在尝试模拟类似于 draw.io 的箭头功能,在鼠标悬停在对象上时,我想在每边的中心显示蓝点,在所有 4 边显示箭头。任何想法如何实现相同的。

在此处输入图像描述

感谢您的回复.. 谢谢。

4

1 回答 1

2

我用正方形做了一个例子。悬停会在每一侧产生十字和箭头。我建议阅读有关 SVG 中路径文档,以了解我是如何绘制这些形状的。

const size = 200,
  margin = 100,
  offset = 10,
  crossesPerSide = 4;
const arrowPath = 'M-5,0 h10 v30 h10 l-15,15 l-15,-15 h10 Z';
const crossPath = 'M-6,-5 l12,10 m0,-10 l-12,10';

const g = d3.select('svg')
  .append('g')
  .on('mouseover', () => {
    g.selectAll('.arrow')
      .data('nesw'.split(''))
      .enter()
      .append('path')
      .classed('arrow', true)
      .attr('d', arrowPath)
      .attr('transform', (d, i) => `
        translate(${margin} ${margin})
        translate(${size / 2} ${size + offset})
        rotate(${i * 90} 0 ${-offset - size / 2})
      `)

    g.selectAll('.cross')
      .data(d3.range(crossesPerSide * 4))
      .enter()
      .append('path')
      .classed('cross', true)
      .attr('d', crossPath)
      .attr('transform', (d, i) => {
        const sideIdx = Math.floor(i / crossesPerSide);
        const crossIdx = i % crossesPerSide;
        const spacePerCross = (size / crossesPerSide);
        return `
          translate(${margin} ${margin})
          rotate(${sideIdx * 90} ${size / 2} ${size / 2})
          translate(${spacePerCross * (crossIdx + 0.5)}, 0)
        `;
      })
  })
  .on('mouseleave', () => {
    g.selectAll('.arrow').remove();
    g.selectAll('.cross').remove();
  });

g.append('rect')
  .attr('x', margin)
  .attr('y', margin)
  .attr('width', size)
  .attr('height', size)
  .attr('stroke', 'black')
  .attr('fill', 'white')
svg {
  border: solid 1px red;
}

.cross {
  stroke: darkblue;
  stroke-width: 2;
  opacity: 0.6;
}

.arrow {
  fill: darkblue;
  opacity: 0.2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="400" height="400"></svg>

于 2020-10-13T07:44:43.190 回答