我在路径上创建“点”时遇到问题,如果我创建超过2个“点”他们开始“合并”,并且在一个简单的直线路径上一切正常。
<path id="path" stroke="black" d="M436.3,583.7C561.4,788.6,726.6,968.7,921,1109.7c99.8,72.4,208.5,134.7,326.5,172.1c127.2,40.3,261.7,48.9,394.4,48
c127.8-0.9,256.5-9.7,381.3-38.6c122.6-28.4,234.3-79.4,340.5-146.2c100.8-63.5,196.8-135.2,303.6-188.6
c107.3-53.6,225.3-84.3,345.6-84.6c214.7-0.5,425.8,102.5,541.2,286.8c13.8,22.1,26,45.1,36.6,68.9c0.8,1.7-1.8,3.3-2.6,1.5
c-92.9-208.4-306.1-339.5-530.6-353c-126-7.6-252.6,18.9-366.7,72.3c-109,51-206.3,122.8-307.2,187.5
c-102.1,65.5-208.5,119-326.3,150c-120.3,31.7-245,43.3-369,46.2c-128,3-257.8-0.9-382.8-31.1c-118.9-28.8-229.5-83.4-331.2-150.7
c-194.1-128.7-362.2-298-492.7-490.7c-16.5-24.4-32.4-49.2-47.7-74.3C432.7,583.6,435.3,582.1,436.3,583.7L436.3,583.7z"/>
<script type="text/javascript"><![CDATA[
var el = document.getElementById("path");
var len = parseInt(el.getTotalLength());
var userValue = parseInt(prompt('Enter Integer from 2 to 100:'));
var modulo = parseInt(len / userValue);
for (i = 0; i < len; i++) {
if (i % modulo ) { continue; }
var dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
dot.setAttributeNS(null, "cx", el.getPointAtLength(i).x );
dot.setAttributeNS(null, "cy", el.getPointAtLength(i).y );
dot.setAttributeNS(null, "r", '25');
dot.setAttributeNS(null, "fill", "red");
document.getElementById("container").appendChild(dot);
}]]></script>
答案 0 :(得分:1)
在HTML中:路径遵循一些曲线,然后沿着相同的曲线返回到创建闭合路径的起点。第一个和最后一个圆圈将在同一点。第二个和倒数第二个圆圈将在同一个地方。等等。您是否打算创建一个不会自行循环的开放路径?例如......
<path id="path" fill="none" stroke="black" d="M436.3,583.7C561.4,788.6,726.6,968.7,921,1109.7c99.8,72.4,208.5,134.7,326.5,172.1c127.2,40.3,261.7,48.9,394.4,48
c127.8-0.9,256.5-9.7,381.3-38.6c122.6-28.4,234.3-79.4,340.5-146.2c100.8-63.5,196.8-135.2,303.6-188.6
c107.3-53.6,225.3-84.3,345.6-84.6c214.7-0.5,425.8,102.5,541.2,286.8c13.8,22.1,26,45.1,36.6,68.9c0.8,1.7-1.8,3.3-2.6,1.5"/>
在JavaScript中:路径的总距离(即getTotalLength())是一个浮点数。圆之间的距离(即getTotaleLength()/(uservalue-1))是一个浮点数。代码将这两个值转换为整数,这些整数会丢失值的小数部分,从而影响后面的计算。一种解决方案是从i步骤i到userValue - 1,然后计算沿第i个圆的路径的距离。例如......
var el = document.getElementById("path");
var totalLength = el.getTotalLength();
var userValue = parseInt(prompt('Enter Integer from 2 to 100:'), 10);
for (i = 0; i < userValue; i++) {
var distance = (i / (userValue - 1)) * totalLength;
var dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
dot.setAttributeNS(null, "cx", el.getPointAtLength(distance).x );
dot.setAttributeNS(null, "cy", el.getPointAtLength(distance).y );
dot.setAttributeNS(null, "r", '25');
dot.setAttributeNS(null, "fill", "red");
document.getElementById("container").appendChild(dot);
}
注意:调用parseInt()函数时,最好指定基数。