我有一个函数可以创建给定参数的圆,但是我想在每按一个按钮时就给它添加标签。
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;
}
我想在按下按钮后将标签添加到圈子中。有没有办法做到这一点。
答案 0 :(得分:1)
看看下面的代码。
我已经在圆上添加了属性data-id,并将函数绑定到了click事件。该函数使用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>