当我练习 oop 时,我注意力不集中,不知道如何继续。 我有两个代码,我需要合并这两个代码。 我需要使用oop的方法来初始化svg的变量。
需要帮助。 谢谢。
function ArrayMaker(svgcx, svgcy ,svgr ,svgstroke ,svgstroke_width ,svgfill ) {
this.svgcx = 100;
this.svgcy = 50;
this.svgr = 40;
this.svgstroke = "red";
this.svgstroke_width = 3;
this.svgfill = "yellow";
this.theArray = [ this, svgcx ,svgcy ,svgr ,svgstroke ,svgstroke_width ,svgfill ];
}
ArrayMaker.prototype = {
someMethod: function () {
alert( 'someMethod called');
},
getArray: function () {
return this.theArray;
}
};
var am = new ArrayMaker( 'one', 'two' );
var other = new ArrayMaker( 'first', 'second' );
alert(am.getArray());
这段代码可以工作:
var cx=100;
var cy=50;
var r=40;
var stroke="red";
var stroke_width=3;
var fill="yellow";
var htm = "<html>";
htm += "<head>";
htm += "<title>test3</title>";
htm += "</head>";
htm += "<body>";
htm += "<svg ";
htm += " version=";
htm += "\"1.1\"";
htm += ">";
htm += "<circle ";
htm += "cx="+cx+" ";
htm += "cy="+cy+" ";
htm += "r="+r+" ";
htm += "stroke="+stroke+" ";
htm += "stroke-width="+stroke_width+" ";
htm += "fill="+fill+" ";
htm += "/>";
htm += "</body>";
htm += "</html>";
document.write(htm);
最佳答案
要使用 JS 创建 SVG 元素,您需要使用 createElementNS()
并使用 SVG 命名空间 ( http://www.w3.org/1999/xhtml
) 创建元素。例如,请参阅我网站上的此演示:http://phrogz.net/SVG/svg_in_xhtml5.xhtml
var svgNS = "http://www.w3.org/1999/xhtml";
function createOn( root, name, attrs ){
var el = document.createElementNS(svgNS,name);
for (var attr in attrs){
if (attrs.hasOwnProperty(attr)) el.setAttribute(attr,attrs[attr]);
}
return root.appendChild(el);
}
var svg = createOn( document.body, 'svg', {viewBox:'-100 -100 200 200'} );
createOn( svg, 'circle', { cx:-60, cy:-50, r:20, fill:'#000' });
请注意,SVG 属性不在任何命名空间中,因此您可以使用 setAttribute()
(正如我上面所做的)或setAttributeNS(null,...)
。但是,对于 SVG 外部指定的属性而言,情况并非如此,例如 XLink 的 href
。为此,您需要使用正确的命名空间创建属性。
关于javascript - 使用js oop和svg绘制循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9609155/