簡體   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