0

I have a simple html file containing an SVG polyline:

Here's my code:

span {
    border: 1px solid red;
}
polyline{
    fill:none;
    stroke:red;
    stroke-width:3
}
 <p>A block element containing an <span>inline element</span></p>
        <svg height="200" width="500">
            <polyline points="0,0 20,0 40,25" />
      </svg>

I would like to start the polyline exactly at the midpoint of my span's right border. How can I do that?

MahmouD Skafi
  • 370
  • 3
  • 15
user32882
  • 5,094
  • 5
  • 43
  • 82
  • Quick attempt - https://jsfiddle.net/bgzr190u/ – Mr T Mar 12 '21 at 14:42
  • @MrT Nice attempt, but if you reduce the width of the browser window you will see that it messes up the polyline positioning. – user32882 Mar 12 '21 at 14:56
  • Another one - https://jsfiddle.net/dmg0r87f/ this one has an issue with overflow though – Mr T Mar 12 '21 at 15:04
  • What do you mean by overflow? – user32882 Mar 12 '21 at 15:06
  • On smaller screens you can see a horizontal scroolbar which can be fixed by setting `overflow: hidden`, but not sure if that is desired outcome - https://jsfiddle.net/fwr3a1ut/ – Mr T Mar 12 '21 at 15:07

1 Answers1

2

This is a very basic idea: you give the svg position:absolute and the same size as the html element overlapped. You calculate the bounding client rect of the span and the position of the point where the polyline shpuld begin. Ypu either translate the polyline or you rewrite the points attribute so that it begins where you want it

let bcr = sp.getBoundingClientRect();
poly.setAttribute("transform",`translate(${bcr.x+bcr.width},${bcr.y+bcr.height/2})`)
svg {
  outline: solid;
  position: absolute;
  top:0;left:0;
}
div {
  width: 500px;
  height: 200px;
}
span {
  border: 1px solid red;
}
polyline {
  fill: none;
  stroke: red;
  stroke-width: 3;
}
<div>
  <p>A block element containing an <span id="sp">inline element</span></p>
</div>
<svg height="200" width="500">
  <polyline id="poly" points="0,0 20,0 40,25" />
</svg>
enxaneta
  • 31,608
  • 5
  • 29
  • 42
  • This looks really good but is the use of javascript really necessary here? – user32882 Mar 12 '21 at 14:48
  • 1
    Also you appear to be calling the id name directly in JS without using the more conventional `getElementById` method. What is that called? I have never seen it... – user32882 Mar 12 '21 at 15:15
  • you can use getElementById or querySelector if you prefer. In this demo I'm using the id because there is less code and - in my opinion - clearer and easier to understand – enxaneta Mar 12 '21 at 15:54
  • https://html.spec.whatwg.org/multipage/window-object.html#named-access-on-the-window-object – Mr T Mar 12 '21 at 16:27
  • Also https://stackoverflow.com/questions/14478102/why-use-document-getelementbyid-when-i-can-directly-refer-to-the-dom-id-in-javas It seems like calling the id by name is a convenience feature which is less robust than `getElementById`. Good to know. – user32882 Mar 12 '21 at 18:57