如何在img中使用JavaScript显示SVG
How to show SVG with JavaScript in img
我有一个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>
,因为它们确实允许脚本编写。
相关文章:
- PHP Javascript显示/隐藏按钮不工作
- 通过javascript显示和更改文本
- 是否可以用JavaScript显示等效的文件夹对话框
- 如何使用javascript显示图像
- BMI计算器以Javascript显示结果
- 单击“JavaScript显示变量”
- Javascript:显示带有复选框值的图像
- 通过ID JavaScript显示随机背景图像
- 无法在qualtrics上使用javascript显示背景图像
- 日期选择器无法使用javascript显示
- javascript 显示空白灰色层
- 页面加载后通过javascript显示图像
- 使用JavaScript显示鼠标的x和y位置
- 用javascript显示html表
- 使用 JavaScript 显示 Laravel's Variable
- javascript显示地理位置
- 搜索XML文件并使用javascript显示结果
- 使用javascript显示文件名上传
- 使用javascript显示隐藏的HTML元素
- 使用jquery和javascript显示PHP中的变量