gpt4 book ai didi

javascript - Canvas 网络的工具提示

转载 作者:可可西里 更新时间:2023-11-01 13:25:59 24 4
gpt4 key购买 nike

我使用 D3.v4 和 Canvas 制作了一个大型布局。由于尺寸原因,我无法真正使用 SVG。

如何为 Canvas 上的元素制作工具提示?

至少,我怎样才能确定鼠标在 Canvas 上的位置?

我尝试使用 this 问题的答案作为灵感来检查鼠标光标在 Canvas 上的位置,然后使用 simulation.find(x,y,radius) 来识别附近的节点。但是,这会返回很多误报,我感觉 HTML 事件和 simulation.find() 的工作方式不同和/或使用不同的坐标标准。

有没有人对此有任何想法或解决方案?

编辑:有人建议看一下 this 问题。我已经尝试过这样做,并且它在某种程度上起作用了。现在的问题是,正如所怀疑的那样,simulation.find(..) 似乎没有使用这些 Canvas 坐标来查找网络中的节点。

出于好奇,这是我用来查找光标和附近节点的当前函数:

canvas = d3.select('canvas')
function getPos(e) {
rect = canvas.node().getBoundingClientRect();
scaleX = width / rect.width;
scaleY = height / rect.height;
x = (e.clientX - rect.left);
y = (e.clientY - rect.top);
node = simulation.find(x,y, 3);
return {
x : x,
y : y,
node : node
};
}

最佳答案

您应该使用内置的 d3.mouse找出 Canvas 中的位置:

d3.select("canvas").on("mousemove", function(d){
var p = d3.mouse(this);
var node = simulation.find(p[0], p[1]);
});

这是一个突出显示离鼠标位置最近的节点的简单示例:

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="600"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;

var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) {
return d.id;
}))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));


var graph = {};
graph.nodes = d3.range(100).map(function(d) {
return {
id: d
}
});
graph.links = d3.range(200).map(function(d) {
return {
source: Math.floor(Math.random() * 100),
target: Math.floor(Math.random() * 100)
};
});

simulation
.nodes(graph.nodes)
.on("tick", ticked);

simulation.force("link")
.links(graph.links);

function ticked() {
context.clearRect(0, 0, width, height);

context.beginPath();
graph.links.forEach(drawLink);
context.strokeStyle = "#aaa";
context.stroke();

context.beginPath();
graph.nodes.forEach(drawNode);
context.fill();
context.strokeStyle = "#fff";
context.stroke();

if (closeNode) {
context.beginPath();
drawNode(closeNode)
context.fill();
context.strokeStyle = "#ff0000";
context.stroke();
}
}

var closeNode;
d3.select("canvas").on("mousemove", function(d){
var p = d3.mouse(this);
closeNode = simulation.find(p[0], p[1]);
ticked();
})

function drawLink(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
}

function drawNode(d) {
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}
</script>

关于javascript - Canvas 网络的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38271595/

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