Javascript:将图像插入html文件中的svg元素中



我在html文档中有一个svg元素,我想在某些交互时将其与图像一起存档,但无论我多么努力,我都无法实现这一点。即使是这里最简单的例子

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body>
<div id = "header" style = "border:1px solid black;">
<svg width="100%" height="100%" id = "map"></svg>
</div>
<script>
var el = document.createElementNS('http://www.w3.org/2000/svg', 'image');
el.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "https://url_of_image_here.com");
el.setAttributeNS(null, 'width', '100');
el.setAttributeNS(null, 'height', '100');
el.setAttributeNS(null, 'x', 20);
el.setAttributeNS(null, 'y', 20);
document.getElementById("map").append(el);
</script>
</body>
</html>

仅生成一个空的<div>。。。我看了所有其他相关的帖子,最后总是得到一个空的<div>(事实上,这个狙击手取自这个问题的另一个答案…(。我做错了什么?此外,如何链接本地图像?

不知道为什么,但通过el.setAttributeNS(null, 'visibility', 'visible');使图像明确"可见"似乎解决了我的问题。。。

最新更新