gpt4 book ai didi

javascript - 如何将文本置于圆圈之上?

转载 作者:行者123 更新时间:2023-11-29 23:03:22 25 4
gpt4 key购买 nike

我有制作圆圈的代码,我想在圆圈上放置文字。

我用这个作为我的例子:https://bl.ocks.org/mbostock/raw/7341714/

    infoHeight = 200
infoWidth = 200

var compareSVG = d3.select(".info-container")
.append("svg")
.attr("class","comparison-svg")
.attr("width", infoWidth)
.attr("height", infoHeight);

var circle = compareSVG.append("g")

circle.append("circle")
.attr("r", circleRadius(d.properties.contextvalue))
.attr("cy", infoHeight/2)
.attr("cx", infoWidth/2)
.style("fill","grey")
.style("stroke","black")
.style("stroke-width","3px")

circle.append("text")
.text(d.properties.contextvalue)
.style("display", "block")
.style("y", infoHeight/2)
.style("x", infoHeight/2)
.style("color","red")
.style("font-size","20px")

圆圈有效,但文本不会出现在它上面。相反,它位于 SVG 元素的左上角。我试过 position: absolute 以及 topleft 并且它保持在同一个 Angular 落。

最佳答案

在 D3 中,attr方法使用 Element.setAttribute 在内部,同时 style使用 CSSStyleDeclaration.setProperty() .

在 SVG 中 <text>元素,xy属性。因此,更改那些 style() attr() 的方法.另外,摆脱那个 .style("display", "block") .

所以,应该是:

circle.append("text")
.text(d.properties.contextvalue)
.attr("y", infoHeight/2)
.attr("x", infoHeight/2)
.style("color","red")
.style("font-size","20px")

这里是你的代码有那个变化:

infoHeight = 200
infoWidth = 200

var compareSVG = d3.select("body")
.append("svg")
.attr("width", infoWidth)
.attr("height", infoHeight);

var circle = compareSVG.append("g")

circle.append("circle")
.attr("r", 50)
.attr("cy", infoHeight / 2)
.attr("cx", infoWidth / 2)
.style("fill", "lightgrey")
.style("stroke", "black")
.style("stroke-width", "3px")

circle.append("text")
.text("Foo Bar Baz")
.attr("y", infoHeight / 2)
.attr("x", infoHeight / 2)
.style("color", "red")
.style("font-size", "20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

最后,注意文字的位置:没有输入(关于圆圈)。如果要居中,请使用 text-anchordominant-baseline :

infoHeight = 200
infoWidth = 200

var compareSVG = d3.select("body")
.append("svg")
.attr("width", infoWidth)
.attr("height", infoHeight);

var circle = compareSVG.append("g")

circle.append("circle")
.attr("r", 50)
.attr("cy", infoHeight / 2)
.attr("cx", infoWidth / 2)
.style("fill", "lightgrey")
.style("stroke", "black")
.style("stroke-width", "3px")

circle.append("text")
.text("Foo Bar Baz")
.attr("y", infoHeight / 2)
.attr("x", infoHeight / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "central")
.style("color", "red")
.style("font-size", "20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - 如何将文本置于圆圈之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55177706/

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