javascript - 如何在 d3 中的 SVG 圆上添加标签?

标签 javascript d3.js

我有一个函数可以创建给定参数的圆圈,但我想在按下按钮时为其添加标签。

function createCircle(cx, cy, radius, color){
// create circle with the given parameters
 var circle =  canvas.append("circle")
    .attr("cx", cx)
    .attr("cy", cy)
    .attr("r", radius)
    .attr("fill", color)
    .text("Hello");
return circle;
}

我有另一个函数,可以在单击按钮时创建一条线

function createLine(x1, y1, x2, y2, color){
var line = canvas.append("line")
    .attr("x1", x1)
    .attr("y1", y1)
    .attr("x2", x2)
    .attr("y2", y2)
    .attr("stroke", color)
    .attr("stroke-width", 1);
return line;

}

我想在按下按钮后向圆圈添加标签。有什么办法可以做到吗。

最佳答案

看看下面的代码。

我向圆圈添加了属性 data-id 并将函数绑定(bind)到单击事件。该函数使用 d3.event 查找事件,获取其目标,从中创建选择并提取 id。

然后只需使用标签创建一个新的选择并为其设置动画即可。

希望对你有帮助!

let svg = d3.select("#my-svg");
let data = [
  {
    key: "01",
    x: 50,
    y: 60,
    r: 40,
    color: "red",
    label: "Hello world!"
  }
];
let handleClick = (d, i) => {
  let target = d3.select(event.target);
  let id = target.attr("data-id")
  let text = d3.select(`#label-${id}`);
    text.transition()
    .duration(500)
    .attr("opacity", text.attr("opacity") === "0" ? 1 : 0)
};
svg
  .selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("id", d => `circle-${d.key}`)
  .attr("data-id", d => d.key)
  .attr("cx", d => d.x)
  .attr("cy", d => d.y)
  .attr("r", d => d.r)
  .attr("fill", d => d.color)
  .on("click", handleClick);
svg
  .selectAll("text")
  .data(data)
  .enter()
  .append("text")
  .style("pointer-events", "none")
  .attr("id", d => `label-${d.key}`)
  .attr("x", d => d.x)
  .attr("y", d => d.y)
  .attr("text-anchor", "middle")
  .attr("fill", "#000")
  .attr("opacity", 0)
  .text(d => d.label);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Label on click</title>
</head>
<body>
  <svg id="my-svg" width="100" height="100"></svg>
</body>
</html>

关于javascript - 如何在 d3 中的 SVG 圆上添加标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55254058/

相关文章:

javascript - 我如何在 Electron-js 中从 Sqlite 数据库中获取数据,然后使用 Document.getElementBy ('id' 显示它).innerHTML

javascript - 表单验证不同步

javascript - 使 D3 小部件可滚动

javascript - D3 - 另一个事件内的事件绑定(bind)

javascript - js 和 d3 中给定键的返回值 - 我必须循环吗?

javascript - 如何使用脚本设置环境变量 [Node.js]

Javascript:对象构造函数中的字符串连接

javascript - 删除对象属性 (VueJs)

javascript - 如何使 d3 折线图中的 x 轴可滚动

css - 使用 dc.js (d3.js) 并尝试在 0 处突出显示 x 轴