d3.js - 在鼠标上添加连接器类似于 draw.io
解决方案
我用正方形做了一个例子。悬停会在每一侧产生十字和箭头。我建议阅读有关 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>
推荐阅读
- python - 选择列中具有特定值的行,并在 pandas 数据框中包含具有 NaN 的行
- java - for循环中的Java特定字符
- google-apps-script - Google Apps 脚本:响应预先存在的电子邮件线程
- docker - 根据环境在 Dockerfiles 中调用不同的命令
- git - 可以从即将删除的分支中剪切一个 git 分支吗?
- email - 如何从 Flutter Web 应用程序发送电子邮件?
- android-intent - 如何让 Spotify 和其他 Android 音乐应用根据意图进行搜索和播放?
- javascript - 当我使用上下文 API 请求突变文件时出错
- javascript - 遍历字符串并替换未按预期工作的空格
- java - 如何转换列表
进入字符串 []