0
我試圖用外部.js文件創建一個SVG(實際上由svg.php
文件創建)。將所有javascript函數直接放在SVG中時,它可以正常工作:動態創建具有外部.js文件的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並在其周圍繪製一個框,示例主要取自How can I draw a box around text with SVG?。)
但是,我想將javascript函數放在外部.js文件中。不幸的是,我不知道在哪裏加載它。在svg.js
中放置函數並在php文件中的其他腳本之前添加一個簡單的<script src="svg.js"></script>
似乎不適用於此技巧。
感謝您的回答。不幸的是,這不起作用,但給我一個「XML解析錯誤:前綴不綁定到命名空間」。 – Daniel
我已經擴展了我的解釋。 –