maytham-ɯɐɥʇʎɐɯ maytham-ɯɐɥʇʎɐɯ - 3 years ago 176
Javascript Question

Implement Div objects on SVG path

I have created a path in Adobe Illustrator and export it to SVG file format.

Now I want to implement Div objects (like circles) on the path like the red circles on the path in the image example below.

I have had difficulty finding a way to do it, How to make such implementation?

SVG code with path data

<div id="pathContainer">

<svg version="1.1" id="Layer_4"
xmlns="" xmlns:xlink=""
x="0px" y="0px" width="595.28px" height="841.89px" viewBox="0 0 595.28 841.89">
<path id="mypath" fill="#FFFFFF" stroke="#F8AC9F" stroke-miterlimit="10" d="M69.429,102.762c2.263,36.997,58.704,58.47,88.784,65.713


Image Example

Answer Source

You will need to use some Javascript. Luckily the SVG DOM provides a function that allows you to get the position of a point n along a path:

var point = mypath.getPointAtLength(n);

So once you have a reference to a path, you can position elements along it using absolute positioning.

pathOnDiv("1", 0.1);

function pathOnDiv(text, pos)
   // Get the coordinates of the point that is the fraction 'pos' along the path
   var  path = document.getElementById("mypath");
   var  pathLength = path.getTotalLength();
   var  loc = path.getPointAtLength(pos * pathLength);

   // Make a div
   var div = document.createElement("div");
   div.textContent = text;
   div.setAttribute("class", "pathDiv"); = loc.x + "px"; = loc.y + "px";

Demo fiddle here

Note that this is a fairly simplistic demo. For instance, it assumes that:

  1. your SVG is at the very top left of the window.
  2. your SVG is not scaled (ie. it is at 1:1).

If those assumptions are not correct, you will need to modify the code a bit.

To correct for assumption #1, you would need to adjust the position of the div by adding in the left and top offset of the SVG on the page.

There are also ways to correct for assumption #2.


A simple way to correct for assumption #1 is to wrap your <svg> and path divs in a container div. If you give that div position: relative, then any pathDivs you put in there will be positioned correctly, and you don't need to worry about adjusting div positions for offset.

Example here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download