简体   繁体   English

使用D3.js在SVG中限制Text元素的宽度

[英]Limiting Width on a Text element in SVG using D3.js

I'm using D3.js. 我正在使用D3.js。 I created a text element in svg. 我在svg中创建了一个文本元素。 I have a element. 我有一个元素。

<text id="text16" class="text" x="xx" y="yy" 
transform="translate(tx,ty)" height="hh" 
text-anchor="left"">DC_AAA_BBB_CCC_XXXX</text>

I want to reduce set the width. 我想减少设置的宽度。 And when the text element width is smaller that the raw text's length(calculated from .getComputedTextLength), I want it to show up to the text element width. 当文本元素的宽度小于原始文本的长度(根据.getComputedTextLength计算)时,我希望它显示为文本元素的宽度。 Such that only up to "DC_AAA_BBB_" is shown when raw text length is longer. 这样,当原始文本长度较长时,最多只能显示“ DC_AAA_BBB_”。

I've tried adding css -> width: 100px; 我试过添加CSS-> width:100px; Also tried adding width attribute in DOM -> width="100px" 还尝试在DOM中添加width属性-> width =“ 100px”

Both did not work. 两者都不起作用。 How can I achieve this? 我该如何实现? Thanks! 谢谢!

You can use clip-path to clip to whatever shape you want, see eg masking-path-01 from the svg testsuite. 您可以使用clip-path剪切到所需的任何形状,例如,参见svg测试套件中的masking-path-01

Relevant parts, defining the clip path: 相关部分,定义剪切路径:

<clipPath id="clip1">
  <rect x="200" y="10" width="60" height="100"/>
  ... you can have any shapes you want here ...
</clipPath>

and then apply the clip path like this: 然后像这样应用剪辑路径:

<g clip-path="url(#clip1)">
  ... your text elements here ...
</g>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM