Skip to content Skip to sidebar Skip to footer

How To Add A Path With 'd' Attributes To A Svg Dynamically

I'm having a problem dynamically generating path elements inside an empty svg with javascript. I'm not interested in using third-party libraries, I'd like to understand how it work

Solution 1:

When you create an object in a different namespace, you have to use document.createElementNS() instead of document.createElement().

JQuery's appendTo() function doesn't invoke createElementNS(), so although your code is creating a perfectly valid SVG element, you aren't seeing anything because the HTML parser doesn't understand it.

This works:

$(function() {
  functioncalculateX(degrees, radius) {
    var radians = Math.PI * degrees / 180;
    returnMath.ceil(radius + (radius * Math.cos(radians)));
  }

  functioncalculateY(degrees, radius) {
    var radians = Math.PI * degrees / 180;
    returnMath.ceil(radius + (radius * Math.sin(radians)));
  }
  var d, opacity, len = 6,
    path, endAngle, degrees = 360 / len,
    startAngle = 270,
    svg = document.getElementById('piechart'),
    ns = 'http://www.w3.org/2000/svg';
  for (var i = 0; i < len; i++) {
    fill = 'rgba(255,0,0,' +parseFloat((i / len).toPrecision(2)) + ')';
    endAngle = (startAngle + degrees) % 360;
    d = 'M100 100 L' + calculateX(startAngle, 100) + ' ' +
      calculateY(startAngle, 100) + ' A100 100 0 0 1 ' +
      calculateX(endAngle, 100) + ' ' +
      calculateY(endAngle, 100) + ' Z';
    path = document.createElementNS(ns,'path');
    path.setAttribute('fill', fill);
    path.setAttribute('d', d);
    svg.appendChild(path);
    startAngle = endAngle;
  }

});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><svgid="piechart"xmlns="http://www.w3.org/2000/svg"width="200"height="200"viewBox="0 0 200 200"></svg>

Post a Comment for "How To Add A Path With 'd' Attributes To A Svg Dynamically"