svg = {
div;
document.querySelector('.svg').innerHTML = '';
document
.querySelector('.svg')
.appendChild(document.createElement('h2')).textContent = '<svg />';
const svg = document
.querySelector('.svg')
.appendChild(document.createElementNS("http://www.w3.org/2000/svg", 'svg'));
svg.setAttribute('viewBox', '0 0 474 488');
const title = document
.querySelector('.svg')
.appendChild(document.createElement('h1'));
function draw(
parent,
node,
{ fillStyle = 'rgba(0, 0, 0, 0.2)', textColor = 'white' } = {}
) {
const children = node.children;
const { x, y, r } = node;
const circle = document.createElementNS(
'http://www.w3.org/2000/svg',
'circle'
);
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
circle.setAttribute('r', r);
circle.setAttribute('fill', fillStyle);
circle.setAttribute('data-name', node.data.name);
parent.appendChild(circle);
if (children) {
const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
for (let i = 0; i < children.length; i++) {
draw(group, children[i], { fillStyle, textColor });
}
group.setAttribute('data-name', node.data.name);
parent.appendChild(group);
} else {
const text = document.createElementNS(
'http://www.w3.org/2000/svg',
'text'
);
text.setAttribute('fill', textColor);
text.setAttribute('font-family', 'Arial');
text.setAttribute('font-size', '8px');
text.setAttribute('text-anchor', 'middle');
text.setAttribute('x', x);
text.setAttribute('y', y);
const name = node.data.name;
text.textContent = name;
parent.appendChild(text);
}
}
draw(svg, data);
function getTitleText(target) {
const name = target.getAttribute('data-name');
if (target.parentNode && target.parentNode.nodeName === 'g') {
const parentName = target.parentNode.getAttribute('data-name');
return `${parentName}-${name}`;
}
return name;
}
let activeTarget = null;
svg.addEventListener('mousemove', evt => {
let target = evt.target;
if (target.nodeName === 'text') target = target.previousSibling;
if (activeTarget !== target) {
if (activeTarget) activeTarget.setAttribute('fill', 'rgba(0, 0, 0, 0.2)');
}
target.setAttribute('fill', 'rgba(0, 128, 0, 0.1)');
title.textContent = getTitleText(target);
activeTarget = target;
});
}