如何绘制带有点的响应式SVG路径?

我正在尝试绘制此 SVG 路径。

如何绘制带有点的响应式SVG路径?

我可以使用 SVG Line 和 Curve 属性使用固定坐标实现固定高度和宽度。

但是,我需要响应式地绘制它,这意味着路径的宽度、线之间的空间、每个点之间的距离以及两侧的曲线都应该是响应式的。

它包含由数字表示的级别,如图所示,路径的长度应由给定的级别数确定。

在尝试以响应方式绘制时,我被困在

  1. 获取线条的起点和终点
  2. 获取曲线的控制点
  3. 响应式调整每个点之间的距离和曲线之间的空间
  4. 根据给定的层数确定路径的长度

我试图通过一些数学计算使用基于父 div 宽度的百分比来完成这些操作。但是,由于其复杂性,它似乎打破了某些或其他情况。

除此之外还有一些其他的事情要做,但这是需要做的事情的顶级版本。

是否有任何直接的方法、公式或计算来实现这一目标? (要么) 有没有其他方法可以绘制这个? (要么) 有没有学习绘制这些类型的 SVG 路径的教程?

xxingx 回答:如何绘制带有点的响应式SVG路径?

创建路径后,您需要计算数字和圆圈在路径上的位置。为此,您需要知道使用 getTotalLength() 方法计算的路径长度。接下来,您需要一个循环来计算路径上数字的位置。为此,我使用了 getPointAtLength() 方法。在每个点上创建一个新的圆(使用)元素和一个新的文本元素。

请阅读代码中的注释。

//constants used to create a new element in svg
const SVG_NS = "http://www.w3.org/2000/svg";
const SVG_XLINK = "http://www.w3.org/1999/xlink";
//the total length of the path
let length= thePath.getTotalLength();
//the number of points on the path
let n = 15;
let step = length/n;


for(let i= 1; i<=n; i++){
//creates a new point on the path at a given length
let point = thePath.getPointAtLength(i*step);
  
//create a new use element (or a circle) and set the center of the circle on the calculated point
let use = document.createElementNS(SVG_NS,'use');
use.setAttributeNS(SVG_XLINK,'xlink:href','#gc');
use.setAttribute("x",point.x);
use.setAttribute("y",point.y); 
//create a new text element on the same point. Thr text content is the i number
let text = document.createElementNS(SVG_NS,'text');
text.setAttribute("x",point.x);
text.setAttribute("y",point.y); 
text.textContent = i;
//append the 2 new created elements to the svg
svg.appendChild(use);
svg.appendChild(text);  
}
svg {
  border: solid;
}
text {
  fill: black;
  font-size: 4px;
  text-anchor: middle;
  dominant-baseline: middle;
}
<svg viewBox="0 0 100 80" id="svg">
  <defs>
  <g id="gc">
    <circle fill="silver" r="3" />
  </g>
  </defs>
  <path id="thePath" fill="none" stroke="black" d="M10,10H70A10,10 0 0 1 70,30H20A10,10 0 0 0 20,50H70A10,70H20" />
</svg>

请注意,由于 svg 元素有一个 viewBox 属性,并且 no with 它占用所有可用宽度,使其具有响应性。

本文链接:https://www.f2er.com/228308.html

大家都在问