将输入从上面定位到svg曲线

时间:2018-04-21 11:19:26

标签: javascript html css html5 svg

我想将输入表单元素放在svg曲线的中心上方shown

曲线以下列形式指定

<svg width="600" height="80" style="border-style: dashed;" xmlns="http://www.w3.org/2000/svg" id="" style="display: none;">
   <defs>
     <marker id="arrow" markerWidth="10" markerHeight="10" refX="0" refY="3" orient="auto" markerUnits="strokeWidth">
       <path d="M0,0 L0,6 L9,3 z" fill="#f00" />
     </marker>
   </defs>
   <path d="M10 40 Q 95 0 200 40" stroke="black" fill="transparent" marker-end="url(#arrow)"/>
</svg>

有可能以某种方式做到吗?我对这么多代码不感兴趣,所以很多想法都可以做到。

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用getBoundingClientRect查找曲线的边界框,然后从那里开始。我在曲线上添加了id,以便轻松找到它。

&#13;
&#13;
function setInputPosition( curve, input ){

  var bb = curve.getBoundingClientRect();
  
  // Since the DOMRect is relative to the viewport,
  // we need to add the amount scrolled to it if we want to absolute
  // position it on the page.
  // I also added half of the curves width to center it horizontally.
  // I used CSS to then align the input around the point,
  // but obviously you could just do that here as well.
  
  input.style.position = 'absolute';
  input.style.top = bb.top + document.body.scrollTop + 'px';
  input.style.left = bb.left + document.body.scrollLeft + bb.width / 2 + 'px';

}

var curve = document.querySelector( '#myPath' );
var input = document.querySelector( '#myInput' );
  
window.addEventListener( 'resize', () => {
  
  setInputPosition( curve, input );
  
});

setInputPosition( curve, input );
&#13;
input {
  
  transform: translate(-50%,-100%);
  
}
&#13;
<svg width="600" height="80" style="border-style: dashed;" xmlns="http://www.w3.org/2000/svg" id="" style="display: none;">
   <defs>
     <marker id="arrow" markerWidth="10" markerHeight="10" refX="0" refY="3" orient="auto" markerUnits="strokeWidth">
       <path d="M0,0 L0,6 L9,3 z" fill="#f00" />
     </marker>
   </defs>
   <path d="M10 40 Q 95 0 200 40" id="myPath" stroke="black" fill="transparent" marker-end="url(#arrow)"/>
</svg>

<input id="myInput" value="centered above curve" />
&#13;
&#13;
&#13;