以编程方式绘制具有特定方位角的SVG图标?

问题描述

我们目前有一张传单地图,绘制了几个点。该服务(由地图消耗)除其他外,还包括静态 svg 图标的坐标和路径。很好。

下一步是创建实际的图标,使其看起来像下面的图标。在此示例中,有3个“组”,每个组有4条“线”。每条“线”都有自己的方位角(角度)。同样,每条“线”都有自己的长度。角度与您看到的角度相同,但长度以英里为单位,因为此图标将在地图中使用。

我什至不知道从哪里开始。一个人如何创建这些图标?理论上,在将图标绘制在地图上之前,将先创建并保存这些图标。有图书馆这样做吗?

enter image description here

解决方法

使用Javascript创建SVG非常简单。在该站点以及网络上的其他地方,都有许多有关如何执行此操作的示例。

例如:

let svg = document.getElementById("icon");

// Add a "line" to the SVG,with a given azimuth,radius and length
function makeLine(azimuth,radius,length)
{
  let circumference = radius * 2 * Math.PI;
  // Create an SVG <circle> element
  let line = document.createElementNS(svg.namespaceURI,"circle");
  line.setAttribute("r",radius);
  line.setAttribute("stroke-dasharray",length + ' ' + circumference);
  line.setAttribute("transform","rotate(" + azimuth + ")");
  // Add it to the <svg> element
  svg.appendChild(line);
}

let LEVEL1 = 93,LEVEL2 = 65,LEVEL3 = 37,LEVEL4 = 9;

makeLine(0,LEVEL4,15);
makeLine(120,15);
makeLine(240,15);

makeLine(310,LEVEL3,50);
makeLine(180,55);

makeLine(290,LEVEL2,95);

makeLine(300,LEVEL1,110);
svg {
  width: 400px;
}

circle {
  fill: none;
  stroke: black;
  stroke-width: 14;
}
<svg id="icon" viewBox="-100 -100 200 200">
</svg>