JavaScript and SVG: Error on createElement()

JavaScript and SVG: Error on createElement()

本文关键字:createElement on Error and SVG JavaScript      更新时间:2023-09-26

所以我所拥有的是一个svg文档,没有HTML,在<defs>...</defs>部分我有我的JavaScript。在其中,有一个创建椭圆弧的函数(尽管我只将它用于圆弧,并且在本例中仅用于圆)和另一个使用前一种方法创建圆的函数。这可能不是目前最优雅的方式,但我稍后会研究它…

现在,然而,当试图通过createElement()创建一个新的元素,我得到在Chrome和Firefox的错误,SVG-DOM-Object不包含该方法。

代码如下:

var SVGObj = document.getElementById('canvas');
function Point(x, y) {
  this.x = x;
  this.y = y;
}
var ids =  new Array();
ids.nextID = nextID;
function nextID() {
  this.push(this.length);
  return this.length;
}
function hypot(pointA, pointB) {
  return Math.sqrt((pointA.x - pointB.x) * (pointA.x - pointB.x) + (pointA.y - pointB.y) * (pointA.y - pointB.y))
}
function arc(center, from, to, fill) {
  if (hypot(center, from) == hypot(center, to))
    radius = hypot(center, from);
  else 
    return false;
  var arch = SVGObj.createElement('path');
  arch.setAttribute('d', 'M ' + center.x + ',' + center.y + //Mittelpunkt
                        ' A ' + radius + ' ' + radius + //Radius
                        ' ' +  (Math.atan((from.y - center.y) / (from.x - center.x)) * 180 / Math.PI) + ' 1 0 ' + //from
                        to.x + ',' + to.y); //to
  arch.setAttribute('id', ids.nextID());
  if(fill) arch.setAttribute('style', 'fill: black');
  SVGObj.appendChild(arch);
  return true;
}
function fullCircle(center, radius, fill) {
  return arc(center, new Point(center.x + radius, center.y + radius), new Point(center.x + radius, center.y + radius), fill);
}

if(!fullCircle(new Point(100, 50), 40, true)) alert("Fehler");

您需要使用document.createElementNS('http://www.w3.org/2000/svg', 'path')在SVG命名空间中创建一个path元素