【问题标题】:Increase circle size depend on text inside SVG增加圆圈大小取决于 SVG 内的文本
【发布时间】:2019-10-09 22:55:54
【问题描述】:

我正在尝试创建带有文本的圆形 SVG。 我用文字创建了以下内容。但是,当我发短信数字增加时,我想缩放 svg 圆圈。

我还创建了以下内容。

<svg height=22 viewBox="0 0 18 18" width=22>
    <circle cx="10" cy="10" fill="#49f9b9" r="7" stroke="black" stroke-width="1" />
    <text x="55%" y="50%" text-anchor="middle" dy="0.45em" font-size="11" fill={textcolor}>5</text>
  </svg>

但是,如果价值增加,现在我想创造一个大圈子。假设 10 或 100 或 5000 那么我想增加圈数取决于它。

如下所示。我将值限制到小数点后 4 位。

如果我传递 4 位数的值,那么它会超出圆圈。

<svg height=22 viewBox="0 0 18 18" width=22>
        <circle cx="10" cy="10" fill="#49f9b9" r="7" stroke="black" stroke-width="1" />
        <text x="55%" y="50%" text-anchor="middle" dy="0.45em" font-size="11" fill="#252525">5000</text>
      </svg>

我试图找到缩放圆圈的方法,但没有成功。

任何帮助将不胜感激。

【问题讨论】:

  • 很明显,这不是你需要的
  • 你为什么要使用svg?一个简单的&lt;div&gt; 会做吗?

标签: javascript css svg


【解决方案1】:

你可以使用 d3 库:

let fontSize = 32; //in px;
let txt = "9999+";

let svg = d3.select("body").append("svg")
    .attr("width", 150)
    .attr("height", fontSize*2);

let text = svg.append("text")
    .attr("x", 70)
    .attr("y", fontSize)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .style("font", "300 "+fontSize+"px arial")
    .text(txt);

let bbox = text.node().getBBox();

let rect = svg.append("rect")
    .attr("x", bbox.x - fontSize/2)
    .attr("y", bbox.y)
    .attr("width", bbox.width + fontSize)
    .attr("height", bbox.height)
    .style("fill", "green")
    .style("fill-opacity", ".3")
    .style("stroke", "#222")
    .style("stroke-width", "3px")
    .style("rx", bbox.height/2);
body {
  margin: 0;
  padding: 0;
}
&lt;script src="https://d3js.org/d3.v3.min.js"&gt;&lt;/script&gt;

来源:https://bl.ocks.org/mbostock/1160929(根据您的需要进行了修改)

【讨论】:

    【解决方案2】:

    我同意@Thomas 的评论。这似乎只需几行 CSS 即可轻松完成。

    <div>
      <span id="text">9999+</span>
    </div>
    
    #text {
      padding: 2px;
      border-radius: 20px;
      border: 5px solid black; 
    }
    

    我没有匹配任何颜色或给它一个背景颜色,但这很简单。对我来说,这似乎是比 SVG 更好的选择,我希望它有所帮助(除非您的目标是专门使用 SVG,否则它不会)。

    【讨论】:

    • 当我们增加文本时,它不会保持圆形,而是变成椭圆形。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多