在鼠标上方添加连接器,类似于draw.io

问题描述

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

enter image description here

感谢您的回复。谢谢。

解决方法

我已经用正方形作了一个例子。悬停时会在两侧产生十字形和箭头。我建议阅读this有关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',crossPath)
      .attr('transform',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>