【问题标题】:Append <text> to <svg> via javascript通过 javascript 将 <text> 附加到 <svg>
【发布时间】:2016-07-24 17:58:00
【问题描述】:

我正在学习 SVG,并且有一个非常简单的问题,我真的很苦恼。 如何将文本附加到 svg 标签? 我想达到以下结果:

Picture

我正在这样做:

svg.append("text")
        .attr("x", width / 2)
        .attr("y", height - marginBottom / 1 * 2 )
        .text("text 2")
        .attr("fill","#808080")
        .attr("text-anchor","middle")
        .css("font-size", "14px");

但是浏览器显示错误:

未捕获的类型错误: svg.append(...).attr(...).attr(...).text(...).attr(...).attr(...).css 不是函数。

但同时对于&lt;line&gt; svg.append 有效:

svg.append("line")
     .attr("y1", height - marginBottom / 3 * 2 )
     .attr("y2", height - marginBottom / 3 * 2 )
     .attr("x1", marginLeft / 3 * 2 )
     .attr("x2", width - 20 )
     .attr("stroke-width", 1)
     .attr("stroke", "#5A97C3");

请帮助我理解。

【问题讨论】:

    标签: javascript html d3.js svg


    【解决方案1】:

    正如错误所解释的:没有名为css 的函数,我想你的意思是stylesvg.style("font-size", "14px");

    【讨论】:

      【解决方案2】:

      不确定这是否是您要查找的内容,但您可以将 SVG 放入容器(例如 div)并在 div 中添加文本元素。示例:

      #myDiv{position:relative;width:200px;color:yellow;border:1px solid green;}
      .abs{position:absolute;}
      #innerDiv1{top:0;left:0px;width:90px;height:15px;border:1px solid purple;}
      #innerDiv2{bottom:10px;left:20%;}
      .rotate {-webkit-transform: rotate(-90deg);-moz-transform: rotate(-90deg);-ms-transform: rotate(-90deg);-o-transform: rotate(-90deg);}
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <div id="myDiv">
        <img id="mySvg" src="http://placekitten.com/200/200" />
        <div id="innerDiv1" class="abs rotate">Text One</div>
        <div id="innerDiv2" class="abs">Text Two</div>
      </div>

      在我的演示中,旋转的文本很不稳定,但如果这个概念可以接受,我会将其作为练习。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-30
        • 2020-01-01
        • 2017-05-10
        • 2014-03-10
        • 2021-10-06
        • 2012-02-14
        • 1970-01-01
        相关资源
        最近更新 更多