如何使用SVG在文本周围绘制框? [英] How can I draw a box around text with SVG?

查看:75
本文介绍了如何使用SVG在文本周围绘制框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个框(rect?),该框使用SVG调整自身大小以适合其中的文本?

How can I create a box (rect?) that resizes itself to fit the the text inside of it using SVG?

推荐答案

很抱歉,答案花了我很长时间,但是我正在学习如何将ECMAScript与XML DOM一起使用.

Sorry the answer took me so long, but I was learning how to use ECMAScript with an XML DOM.

好的.因此,假设您的文档结构如下:

Alright. So suppose you have your document structure like so:

<svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:svg="http://www.w3.org/2000/svg"
 xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
 xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
 version="1.1"

 width="800"
 height="600"
 id="example_text">

    <g id="layer1">

        <text
         x="123.4"
         y="567.8"
         id="text_holder">

            <tspan id="tspan1">Text</tspan>
            <tspan id="tspan2">More text</tspan>

        </text>
    </g>
    <script type="text/ecmascript">

function create_from_rect (client_rect, offset_px) {
    if (! offset_px) {offset_px=0;}
    var box = document.createElementNS(
        document.rootElement.namespaceURI,
        'rect'
    );

    if (client_rect) {
        box.setAttribute('x', client_rect.left - offset_px);
        box.setAttribute('y', client_rect.top - offset_px);
        box.setAttribute('width', client_rect.width + offset_px * 2);
        box.setAttribute('height', client_rect.height + offset_px * 2);
    }

    return box;
}

function add_bounding_box (text_id, padding) {
    var text_elem = document.getElementById(text_id);
    if (text_elem) {
        var f = text_elem.getClientRects();
        if (f) {
            var bbox = create_from_rect(f[0], padding);
            bbox.setAttribute(
                'style',
                'fill: none;'+
                'stroke: black;'+
                'stroke-width: 0.5px;'
            );
            text_elem.parentNode.appendChild(bbox);
        }
    }
}

add_bounding_box('text_holder', 5);

</script>
</svg>

在根<svg>元素的底部添加<script>标记会导致它在其上方创建DOM结构之后执行,就像网页上的JavaScript一样.

Adding the <script> tag at the bottom of the root <svg> element causes it to execute after it's created the DOM structure above it, just like JavaScript on a web page.

这篇关于如何使用SVG在文本周围绘制框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆