我需要使用SVG从一点(x0,y0)
到另一点绘制漂亮的描边箭头(x1,y1)
,就像图片上的那个一样。
我能想象的唯一方法是使用带有标记的线(基本上是两条线来模拟笔触和填充),但是由于笔触重叠,因此看起来很难看。
理想情况下,线条和标记都应该使用相同的颜色填充,并且应该具有相同的笔触颜色,并且整体箭头宽度可以固定(但是如果我也可以对其进行参数化的话,那会很酷)。基本上,它的外观应与提供的图片相同,并且只需提供两个点的坐标即可绘制。可能吗?
我很无聊,所以你去。我编写了一个函数来生成正确形状的路径。
您只需要给它“从”和“到”坐标,线宽,箭头宽度和箭头长度即可。
请享用!
var from = {x: 50, y: 250};
var to = {x: 250, y: 100};
var lineWidth = 30;
var arrowheadWidth = 60;
var arrowheadLength = 50;
var svg = document.getElementById("test");
drawArrow(svg, from, to, lineWidth, arrowheadWidth, arrowheadLength);
function drawArrow(svg, from, to, lineWidth, arrowheadWidth, arrowheadLength)
{
var dx = to.x - from.x;
var dy = to.y - from.y;
// Calculate the length of the line
var len = Math.sqrt(dx * dx + dy * dy);
if (len < arrowheadLength) return;
// The difference between the line width and the arrow width
var dW = arrowheadWidth - lineWidth;
// The angle of the line
var angle = Math.atan2(dy, dx) * 180 / Math.PI;
// Generate a path describing the arrow. For simplicity we define it as a
// horizontal line of the right length, and starting at 0,0. Then we rotate
// and move it into place with a transform attribute.
var d = ['M', 0, -lineWidth/2,
'h', len - arrowheadLength,
'v', -dW / 2,
'L', len, 0,
'L', len - arrowheadLength, arrowheadWidth / 2,
'v', -dW / 2,
'H', 0,
'Z' ];
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", d.join(' '));
path.setAttribute("transform", "translate("+from.x+","+from.y+") rotate("+angle+")");
path.setAttribute("class", "arrow-line");
svg.appendChild(path);
}
.arrow-line {
fill: gold;
stroke: black;
stroke-width: 6;
}