Tuhn
Tuhn

Reputation: 21

JavaScript and SVG: Error on createElement()

So what I have is an SVG-Document with no HTML what-so-ever and in the <defs>...</defs>-section I have my JavaScript. In it, there is a function to create elliptical arcs (although I will only use it for circular arcs and, in this example, solely for a circle) and another function to create a circle using the former method. That might not be the most elegant way for now, but I'll look into that later...

Now however, while trying to create a new Element via createElement() I get in both Chrome and Firefox the error that the SVG-DOM-Object does not contain that method.

Here's the code:

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");

Upvotes: 2

Views: 668

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

You need to use document.createElementNS('http://www.w3.org/2000/svg', 'path') to create a path element in the SVG namespace.

Upvotes: 8

Related Questions