I've got SVG code that aligns properly if I write the SVG into the html document, and then view the document:
<html>
<head>
  <script type="text/javascript" src="jquery-1.12.2.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div id="stage">
  <svg width="100" height="100">
  <defs>
    <marker id="arrow-1" markerWidth="4" markerHeight="3" markerUnits="strokeWidth" refx="1" refy="5" viewBox="0 0 10 10" orient="auto">
      <path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke"></path>
    </marker>
  </defs>
  <path d="M 0,10 L 90,10" stroke-width="2" stroke="red" marker-end="url(#arrow-1)"></path>
  </svg>
  </div>
</body>
</html>
This works great, and renders this:

Notice that in the working output, the marker-end is properly aligned with the stroke
I then try to produce the exact same SVG structure with JavaScript:
  var arrowID = 0;
  function drawArrow() {
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute("width",100);
    svg.setAttribute("height",100);
    var defs = document.createElementNS(ns, "defs");
    var marker = document.createElementNS(ns, "marker");
    var id = "arrow-" + arrowID++;
    marker.setAttribute("id", id);
    marker.setAttribute("markerWidth", 4);
    marker.setAttribute("markerHeight", 3);
    marker.setAttribute("markerUnits", "strokeWidth");
    marker.setAttribute("refx", 1);
    marker.setAttribute("refy", 5);
    marker.setAttribute("viewBox", "0 0 10 10");
    marker.setAttribute("orient", "auto");
    var path = document.createElementNS(ns, "path");
    path.setAttribute("d","M 0 0 L 10 5 L 0 10 z");
    path.setAttribute("fill","context-stroke");
    marker.appendChild(path);
    defs.appendChild(marker);
    svg.appendChild(defs);
    var instance = document.createElementNS(ns, "path");
    // todo set actual start and end
    instance.setAttribute("d", "M 0,10 L 90,10");
    instance.setAttribute("stroke-width", "2");
    instance.setAttribute("stroke", "red");
    instance.setAttribute("marker-end", "url(#"+id+")");
    svg.appendChild(instance);
    document.getElementById("stage").appendChild(svg);
  }
Even though the SVG that ends up on the page is correct (identical to what is above):

The rendered SVG is wrong, and looks like this:

Notice that in the failed output, the marker-end is not aligned properly with the stroke.
What is missing from the JavaScript code that is present in the hard-coded HTML rendering? Why does the JavaScript render a mis-aligned marker end?
Here's everything in a fiddle: fiddle
SVG is case sensitive. The correct attribute names are refX and refY.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With