javascript
复制代码
function getXy(dom, pos) {
var obj = {x : 0, y : 0};
if(pos == 'button') {
obj.x = dom.offsetLeft + dom.offsetWidth / 2;
obj.y = dom.offsetTop + dom.offsetHeight;
}else if(pos == 'left') {
obj.x = dom.offsetLeft;
obj.y = dom.offsetTop + dom.offsetHeight / 2;
}else if(pos == 'right') {
obj.x = dom.offsetLeft + dom.offsetWidth;
obj.y = dom.offsetTop + dom.offsetHeight / 2;
}else if(pos == 'top') {
obj.x = dom.offsetLeft + dom.offsetWidth / 2;
obj.y = dom.offsetTop;
}
return obj;
}
function connectEdges(id1, id2, color = 'red', width = '0.5' , pos1 = 'right', pos2 = 'left') {
const dom1 = document.getElementById(id1);
const dom2 = document.getElementById(id2);
const svg = document.getElementById('svg-container');
var objXy1 = getXy(dom1, pos1);
var objXy2 = getXy(dom2, pos2);
// 创建SVG线条
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', objXy1.x);
line.setAttribute('y1', objXy1.y);
line.setAttribute('x2', objXy2.x);
line.setAttribute('y2', objXy2.y);
line.setAttribute('stroke', color); // 线条颜色
line.setAttribute('stroke-width', width); // 线条宽度
// 将线条添加到SVG容器中
svg.appendChild(line);
}
// 这是我自己的业务代码
for(var i = 0 ; i < data.length ; i++) {
var obj = data[i];
if(obj.source != obj.target){
if(obj.target.indexOf('配偶') != -1) {
connectEdges(obj.source, obj.target, 'red', 2, 'right', 'left');
}else{
connectEdges(obj.source, obj.target, 'blue', 0.5, 'button', 'top');
}
}
}