Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createSVGPoint is not a function?

I need to get the SVGPoint of an <svg> element but for some reason, it doesn't work in my scenario.

Consider the following HTML

<body>

  <svg id="inline">

  </svg>
</body>

And the javascript

var s1 = document.getElementById('inline');
console.log('point', s1.createSVGPoint());

var s2 = document.createElement("svg");
s2.setAttribute("id", "inserted");
document.getElementsByTagName('body')[0].appendChild(s2);
console.log('point2', s2.createSVGPoint());  

The first "point" gets outputtet as expected but the "point2" output prints an error in chrome:

Uncaught TypeError: s2.createSVGPoint is not a function

I've created a small plunker to demonstrate:

http://plnkr.co/edit/fh9kEppA4lR5hY7eA22x?p=preview

like image 396
Per Hornshøj-Schierbeck Avatar asked Oct 26 '15 08:10

Per Hornshøj-Schierbeck


1 Answers

Ok i figured out what was wrong. When creating an SVG element dynamically, you need to tell the browser that it is of a different namespace than the "normal" html elements. I need to create the element like this:

document.createElementNS('http://www.w3.org/2000/svg', 'svg');

When you write the HTML inline, the browser somehow understands and infers the correct namespace.

If you like me, encountered this working with Angular2, there is currently (alpha 38-alpha44) a bug that prevents svg elements from getting created correctly, which is actually the root of my problem. In case you're also here because of that bug, check this out:

https://github.com/angular/angular/issues/4506

like image 200
Per Hornshøj-Schierbeck Avatar answered Sep 25 '22 14:09

Per Hornshøj-Schierbeck