gpt4 book ai didi

d3.js - 使用 D3 缩放和平移时如何将 HTML 元素与 SVG 元素一起翻译

转载 作者:行者123 更新时间:2023-12-01 10:23:18 29 4
gpt4 key购买 nike

我正在使用 D3 在 SVG Canvas 上绘制一堆元素,以及 html 中的工具提示。然后我使用 zoom 允许在 Canvas 上平移/缩放。我希望工具提示跟随圆圈的位置。我似乎无法弄清楚如何计算它。

相关代码

const svg = select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');

// Define the div for the tooltip
const tooltip = select('body')
.append('div')
.attr('class', 'tooltip')
.style('opacity', 0);

const g = svg.append('g')
.attr('width', width)
.attr('height', height);


const zoomHandler = zoom()
.scaleExtent([1 / 10, 100])
.on('zoom', () => {
g.attr('transform', event.transform);
const { x, y, k } = event.transform;
tooltip.attr('data-offset-x', x);
tooltip.attr('data-offset-y', y);
tooltip.attr('data-offset-k', k);
});

zoomHandler(svg);

let overTooltip = false;

const moveTooltip = (d) => {
if (!overTooltip) return;
tooltip.transition()
.duration(100)
.style('opacity', 0.9);

const x = parseInt(tooltip.attr('data-offset-x') || 0, 10);
const y = parseInt(tooltip.attr('data-offset-y') || 0, 10);
const k = parseInt(tooltip.attr('data-offset-k') || 0, 10);
tooltip.html(d.id)
.style('left', `${(d.x / k + x)}px`)
.style('top', `${(d.y / k + y - radius(d) - 5)}px`);
};

const node = g.append('g')
.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.attr('r', radius)
.attr('fill', d => (colors[d.type]))
.on('mouseover', (d) => {
overTooltip = true;
moveTooltip(d);
})
.on('mousemove', moveTooltip)
.on('mouseout', () => {
overTooltip = false;
tooltip.transition()
.duration(100)
.style('opacity', 0);
})

最佳答案

想通了!在 this 上使用 getBoundingClientRect() 获取 SVG 元素的绝对位置

function onMouseOverCircle(d) {
const {
x, y, width,
} = this.getBoundingClientRect();

tooltip.transition()
.duration(100)
.style('opacity', 0.9);

tooltip.html(d.id)
.style('left', `${x + width / 2}px`)
.style('top', `${y - 10}px`);
}

const node = g.append('g')
.attr('stroke', '#fff')
.attr('stroke-width', 1.5)
.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.attr('r', radius)
.attr('fill', d => (colors[d.type]))
.on('mouseover', onMouseOverCircle)
.on('mouseout', () => {
tooltip.transition()
.duration(100)
.style('opacity', 0);
})

关于d3.js - 使用 D3 缩放和平移时如何将 HTML 元素与 SVG 元素一起翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52251084/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com