如何在img中使用JavaScript显示SVG

How to show SVG with JavaScript in img

本文关键字:JavaScript 显示 SVG img      更新时间:2023-09-26

我有一个php文件,它发送一个SVG头并部分使用JavaScript绘制自己。当我直接在浏览器中显示SVG时,一切都很好。然而,当我将其嵌入到<img>中时,JavaScript似乎不会被执行。也许我做错了什么?

以下是php文件(testsvg.php):

<?php
header('Content-type: image/svg+xml');
?>
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<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">
            <?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/JavaScript主要取自How can I draw a box around text with SVG?)

当我直接在浏览器中打开此文件时,例如使用http://localhost/testsvg.php?text=Test时,它会在文本Test周围绘制一个适当的框。

但是,当我用<img>嵌入它时,例如用<img src="testsvg.php?text=Test" alt="">,它不会显示框。

为了保护用户的隐私,脚本不在图像中运行。还有其他限制。

当考虑图像时,有一个心理模型"如果我使用光栅图像,我能做到吗"会有所帮助?如果你记住这一点,你不会错得太多,因为这基本上是浏览器实现的模型。

您的替代方案是使用<object><iframe>标记,而不是<img>,因为它们确实允许脚本编写。