繁体   English   中英

使用外部.js文件动态创建SVG

[英]Dynamically create SVG with external .js-file

我正在尝试使用外部.js文件创建SVG(实际上是由svg.php文件创建)。 将所有JavaScript函数直接放入SVG时,它可以正常工作:

<?php
header('Content-type: image/svg+xml');
?>
<svg
 xmlns="http://www.w3.org/2000/svg"
 version="1.1"
 width="800"
 height="600"
 id="example_text">
    <g id="layer1">
        <text
         x="100"
         y="100"
         id="text_holder"
         style="font-size: 12pt;">
            <?php echo filter_input(INPUT_GET, 'text'); ?>
        </text>
    </g>
    <script type="text/javascript">
        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', 10);
    </script>
</svg>

可以加载例如svg.php?text=Test (哪个会创建SVG并在其周围绘制一个框。该示例主要取自我如何使用SVG在文本周围绘制一个框?)

但是,我想将javascript函数放在一个外部.js文件中。 不幸的是,我不知道在哪里加载它。 将函数放在svg.js ,并在php文件中的其他脚本之前添加一个简单的<script src="svg.js"></script>似乎并不成功。

在SVG中, <script>标签使用xlink:href而不是src指向外部脚本文件,因此您需要

<script xlink:href="svg.js"/>

如果尚未定义xlink命名空间,则需要通过添加xmlns:xlink="http://www.w3.org/1999/xlink"作为根<svg>元素的属性来进行定义。 例如

<svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 version="1.1"
 width="800"
 height="600"
 id="example_text">
...

暂无
暂无

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

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