如何制作自定义SVG路径?

3
我使用这段代码制作了一条曲线的SVG路径。
const bezierWeight = 0.6;
var boxPath = document.getElementById("boxPath_"+edge.id);
var x1 = edge.x1;
var y1 = edge.y1;
var x4 = edge.x4;
var y4 = edge.y4;
var dx = (x4 - x1) * bezierWeight;
var x2 = x1 - dx;
var x3 = x4 + dx;
var boxData = `M${x1} ${y1} C ${x2} ${y1} ${x3} ${y4} ${x4} ${y4}`;
boxPath.setAttribute("d", boxData);

我希望从x1,y1x4,y4这两个点之间生成SVG路径,代码会得到以下结果:

输入图像描述

但我想得到如下的效果:

输入图像描述

如何实现这一点?


刚刚添加了一个带箭头示例的代码片段。请标记正确答案。 - Michael Rovinsky
2个回答

4

getCubicBezierPath 正好可以满足您的需求:

const from = {x: 20, y: 20};
const to = {x: 150, y: 100};

const getCubicBezierPath = (p1, p2) => {
  const midY = (p1.y + p2.y) / 2;
    return `M ${p1.x},${p1.y} 
    C ${p1.x},${midY} ${p2.x},${midY} ${p2.x},${p2.y}`;
};

const svg = d3.select('svg');
svg.append('circle')
    .attr('cx', from.x) 
  .attr('cy', from.y)
  .attr('r', 3)
  .style('fill', 'red')
  
svg.append('circle')
    .attr('cx', to.x)   
  .attr('cy', to.y)
  .attr('r', 3)
  .style('fill', 'red')  
  
svg.append('path')
    .attr('d', getCubicBezierPath(from, to))
  .style('stroke', 'blue')  
  .style('fill', 'none')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="200" height="150">
</svg>


1
太好了!您能否建议如何在一端添加箭头? - Satyaki Das

2
一条带有箭头标记的路径:

const from = {x: 20, y: 20};
const to = {x: 50, y: 100};

const getCubicBezierPath = (p1, p2) => {
  const midY = (p1.y + p2.y) / 2;
    return `M ${p1.x},${p1.y} 
    C ${p1.x},${midY} ${p2.x},${midY} ${p2.x},${p2.y}`;
};

const svg = d3.select('svg');
svg.append('circle')
    .attr('cx', from.x) 
  .attr('cy', from.y)
  .attr('r', 3)
  .style('fill', 'red')
  
svg.append('circle')
    .attr('cx', to.x)   
  .attr('cy', to.y)
  .attr('r', 3)
  .style('fill', 'red')  
  
svg.append('path')
    .attr('d', getCubicBezierPath(from, to))
  .attr('marker-end', 'url(#arrow-head)')
  .style('stroke', 'blue')  
  .style('fill', 'none')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="200" height="150">
<defs>
    <marker id="arrow-head" 
          viewBox="0 0 12 12"
          refX="12" 
          refY="6"
          orient="auto"
          markerUnits="strokeWidth"
          markerWidth="12" markerHeight="12">
      <path d="M 0 0 L 12 6 L 0 12 z" fill="blue"/>
    </marker>
  </defs>
</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接