在Svg中获取String的像素长度

编程入门 行业动态 更新时间:2024-10-28 20:26:34
本文介绍了在Svg中获取String的像素长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用SVG。我需要知道字符串长度(以像素为单位)才能进行一些对齐。如何以像素为单位获取字符串的长度?

I'm currently working with SVG. I need to know the string length in pixels in order to do some alignment. How can I do to get the length of a string in pixel ?

更新:感谢nrabinowitz。基于他的帮助,我现在可以获得动态添加文本的长度。这是一个例子:

Update: Thanks to nrabinowitz. Based on his help, I can now get the length of dynamic-added text. Here is an example:

<svg id="main" xmlns="www.w3/2000/svg" xmlns:xlink="www.w3/1999/xlink" version="1.1" width="1020" height="620" viewBox="0 0 1020 620" onload="startup(evt)"> <script> <![CDATA[ var startup = function (evt) { var width; var svgNS = "www.w3/2000/svg"; var txtNode = document.createTextNode("Hello"); text = document.createElementNS(svgNS,"text"); text.setAttributeNS(null,"x",100); text.setAttributeNS(null,"y",100); text.setAttributeNS(null,"fill","black"); text.appendChild(txtNode); width = text.getComputedTextLength(); alert(" Width before appendChild: "+ width); document.getElementById("main").appendChild(text); width = text.getComputedTextLength(); alert(" Width after appendChild: "+ width) document.getElementById("main").removeChild(text); } //]]> </script> </svg>

推荐答案

我一直在想这个,我当时令人惊喜地发现,根据SVG规范,有一个特定的功能可以返回此信息: getComputedTextLength( )

I've been wondering this too, and I was pleasantly surprised to find that, according to the SVG spec, there is a specific function to return this info: getComputedTextLength()

// access the text element you want to measure var el = document.getElementsByTagName('text')[3]; el.getComputedTextLength(); // returns a pixel integer

工作小提琴(仅在Chrome中测试): jsfiddle/jyams/

Working fiddle (only tested in Chrome): jsfiddle/jyams/

更多推荐

在Svg中获取String的像素长度

本文发布于:2023-08-02 08:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1276189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:像素   长度   Svg   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!