[英]How to dynamically add an element to HTML5 SVG?
我已經閱讀了一些與此類似的問題,但我無法讓我的代碼正常工作。 當用戶單擊 SVG 區域時,我想添加一個 SVG 元素。
這是我的 HTML5 和 SVG,它正確渲染:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="svgdraw.js"></script>
</head>
<body>
<svg id="canvas" width="500" height="500">
<circle cx="80" cy="80" r="50" fill="blue"/>
</svg>
</body>
</html>
這是在點擊事件上執行的 JavaScript:
var svgDocument = document.getElementById('canvas');
var svgns = "http://www.w3.org/2000/svg";
var shape = svgDocument.createElementNS(svgns,"circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
document.getElementById('canvas').appendChild(shape);
在 Google Chrome 中,我收到一條錯誤消息,指出createElementNS
不存在。 但是,如果我刪除所有NS
和null
,我也無法正常工作。 這樣做的正確方法是什么? 不同瀏覽器有區別嗎?
據我所知createElementNS()
是document
變量的一部分,請嘗試:
var shape = document.createElementNS(svgns,"circle");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.