使用SVG的箭头 [英] Block arrow using SVG

查看:618
本文介绍了使用SVG的箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用SVG从一个点(x0,y0)到另一个(x1,y1)绘制漂亮的描边箭头,就像图片上的那个一样.

I need to draw nice stroked block arrow using SVG from one point (x0,y0) to another (x1,y1), like the one on the picture.

我能想象的唯一方法是使用带有标记的线(基本上是两条线来模拟笔划和填充),但是由于笔划重叠,因此看起来有点难看.

The only way I can imagine is to use a line (two lines basically to simulate stroke and fill) with marker, but it looks kind of ugly due to overlaping strokes.

理想情况下,线条和标记都应该使用相同的颜色填充,并且应该具有相同的笔触颜色,并且整体箭头宽度可以固定(但是如果我也可以将其参数化,那将会很酷).基本上,它的外观应与提供的图片相同,并且只需提供两个点的坐标即可绘制. 甚至有可能吗?

Ideally both line and marker should be filled with the same color and should have the same stroke color, and overall arrow width can be fixed (but if I could parametrize that as well it would be cool). Basically it should look the same as on picture provided and should be able to be drawn by just providing coordinates of two points. Is it even possible?

推荐答案

我很无聊,所以就到这里了.我编写了一个函数来生成正确形状的路径.

I was bored, so here you go. I have written a function to generate a path of the right shape.

您只需要给它从"和到"坐标,线宽,箭头宽度和箭头长度即可.

You just need to give it the "from" and "to" coords, the line width, arrowhead width, and arrowhead length.

享受!

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;
}

<svg id="test" width="300" height="300">
</svg>

这篇关于使用SVG的箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆