0

I am trying to run this function that takes a path and converts it to a polygon:

function polygonSampledFromPath(path,samples){
  var doc = path.ownerDocument;
  var poly = doc.createElementNS('http://www.w3.org/2000/svg','polygon');

  var points = [];
  var len  = path.getTotalLength();
  var step = step=len/samples;
  for (var i=0;i<=len;i+=step){
    var p = path.getPointAtLength(i);
    points.push( p.x+','+p.y );
  }
  poly.setAttribute('points',points.join(' '));
  return poly;
}


var path = "m247.96255,140.77197c28.82227,-82.68753 141.75,0 0,106.31247c-141.75005,-106.31247 -28.82213,-189 0,-106.31247z"

polygonSampledFromPath(path,30);

However I keep getting this error which somehow leads me to assume that I am passing wrong path format in my path variable.

Uncaught TypeError: Cannot read property 'createElementNS' of undefined

Any ideas?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • `var doc = path.ownerDocument;` doesn't exist in your document. Check for the object. – Afzaal Ahmad Zeeshan Sep 01 '14 at 17:36
  • 1
    Path is a string, and doesn't have an `ownerDocument` property. Maybe you're expecting it to be an element? It's not clear what you're trying to do. – Rob Lourens Sep 01 '14 at 17:37
  • `path.ownerDocument` is `undefined`, I think your hunch is correct. – Alberto Zaccagni Sep 01 '14 at 17:37
  • @AlbertoZaccagni How would I just pass a path into the above function then? – nicholaswmin Sep 01 '14 at 17:37
  • I honestly don't have any idea of what a `path` is. I just saw what caused your problem. Googling around I found this, it might give you some clues: http://bl.ocks.org/david4096/5661131 I also found out your exact snippet of code, so there should be other examples. – Alberto Zaccagni Sep 01 '14 at 17:42

1 Answers1

2

Replace

var doc = path.ownerDocument;
var poly = doc.createElementNS('http://www.w3.org/2000/svg','polygon');

by

var poly = document.createElementNS('http://www.w3.org/2000/svg','polygon');
Robert Longson
  • 118,664
  • 26
  • 252
  • 242