技术问询:将输入表单元素定位至SVG曲线中心上方
Let's walk through how to get your input form perfectly centered above the middle of that SVG curve. Here's a step-by-step solution tailored to your code:
Step 1: Calculate the Curve's Exact Midpoint
Your SVG uses a quadratic Bezier curve (Q command) with these key points:
- Start point:
(10, 40) - Control point:
(95, 0) - End point:
(200, 40)
For a quadratic Bezier, the midpoint (at t=0.5, the center of the curve) is calculated with this formula:
midpoint.x = (start.x + 2*control.x + end.x) / 4 midpoint.y = (start.y + 2*control.y + end.y) / 4
Plugging in your values gives us:
midpoint.x = (10 + 2*95 + 200) / 4 = 100 midpoint.y = (40 + 2*0 + 40) / 4 = 20
So the center of your curve sits at (100, 20) in SVG coordinates.
Step 2: Position the Input with CSS
We'll use a relative container to anchor the input, then absolute positioning to place it exactly where we want. Here's the full working code:
<div style="position: relative; width: 600px;"> <!-- Fixed SVG (removed duplicate style attribute and hidden display) --> <svg width="600" height="80" style="border-style: dashed;" xmlns="http://www.w3.org/2000/svg"> <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="#000" fill="none" marker-end="url(#arrow)" /> </svg> <!-- Input centered above the curve's midpoint --> <input type="text" placeholder="Your input here" style=" position: absolute; left: 100px; top: 20px; width: 140px; padding: 8px; transform: translate(-50%, -100%); border: 1px solid #ccc; border-radius: 4px; " /> </div>
Key Notes:
- The
transform: translate(-50%, -100%)is magic here:-50%shifts the input left by half its width, centering it horizontally over the curve's midpoint.-100%moves it up by its full height, so the bottom edge of the input sits just above the curve's center point.
- Adjust the input's
width,padding, or change-100%to-120%if you want more space between the input and the curve.
For Dynamic/Complex Curves
If your SVG path is longer or changes dynamically, use JavaScript to calculate the midpoint automatically:
const path = document.querySelector('svg path'); const totalLength = path.getTotalLength(); const midPoint = path.getPointAtLength(totalLength / 2); const input = document.querySelector('input'); input.style.left = `${midPoint.x}px`; input.style.top = `${midPoint.y}px`; input.style.transform = 'translate(-50%, -100%)';
This works for any path, not just quadratic Beziers.
内容的提问来源于stack exchange,提问作者Peter

