svg圈没有用javascript绘制 [英] svg circle not being drawn with javascript

查看:86
本文介绍了svg圈没有用javascript绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在HTML中使用javascript来处理svg操作。我写了下面的代码,虽然它生成了正确的html,但是在浏览器中没有看到任何输出,也没有看到任何错误。 <!DOCTYPE html>
< html>
< head>
< / head>
< body>
< script>
var svg1 = document.createElement(svg);
svg1.setAttribute(height,200);
svg1.setAttribute(width,500);
document.body.appendChild(svg1);
var circles = document.createElement(circle);
circles.setAttribute(cx,20);
circles.setAttribute(cy,20);
circles.setAttribute(r,20);
svg1.appendChild(圈子);
< / script>
< / body>
< / html>

我哪里错了?提前感谢。

解决方案

SVG元素需要使用SVG XML名称空间创建。您可以使用 createElementNS 并使用 http://www.w3.org/2000/svg 命名空间来完成此操作:

 <!DOCTYPE html> 
< html>
< head>
< / head>
< body>
< script>
var svg1 = document.createElementNS(http://www.w3.org/2000/svg,svg);
svg1.setAttribute(height,200);
svg1.setAttribute(width,500);
document.body.appendChild(svg1);
var circles = document.createElementNS(http://www.w3.org/2000/svg,circle);
circles.setAttribute(cx,20);
circles.setAttribute(cy,20);
circles.setAttribute(r,20);
svg1.appendChild(圈子);
< / script>
< / body>
< / html>


I have been trying to do a hello world for svg manipulation using javascript in HTML. I have written the below code and although it generates the correct html, I don't see any output in the browser, nor do I see any error.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElement("svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElement("circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

Where am I going wrong? thanks in advance.

解决方案

SVG elements need to be created with the SVG XML namespace. You can do that using createElementNS and using the http://www.w3.org/2000/svg namespace:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

这篇关于svg圈没有用javascript绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆