动态查找SVG的路径

Dynamically find the path of SVG

我有这个 SVG 文件

我想知道直线的方程式。可能吗?我需要方程式在这条线上的不同位置动态添加一些 SVG 点。所以,在那种情况下,我知道 x 值,但我需要计算 y 值。

这是 SVG 文件的来源:

<?xml version="1.0" encoding="UTF-8"?>
<svg width="1366px" height="332px" viewBox="0 0 1366 332" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- Generator: Sketch 55.1 (78136) - https://sketchapp.com -->
    <title>@0.5xTimeline - Deactivated</title>
    <desc>Created with Sketch.</desc>
    <g id="-Design---Desktop" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="02-About-Us" transform="translate(0.000000, -989.000000)" fill-rule="nonzero" stroke="#EFEFEF" stroke-width="11">
            <g id="HISTORY" transform="translate(-28.000000, 813.000000)">
                <g id="Graphic---Timeline" transform="translate(0.000000, 182.000000)">
                    <path d="M0,38.8855723 C99.4313478,-10.5096141 202.976477,-12.845873 310.635387,31.8767959 C472.123752,98.9607991 512.237609,231.556286 773.130376,301.214063 C1034.02314,370.871839 1355.95795,229.12379 1417,164.042295" id="Timeline---Deactivated"></path>
                </g>
            </g>
        </g>
    </g>
</svg>

如果你知道你有一个 函数,那是一条只走 left-to-right 并且永远不会折返的路径,那么你可以沿着它扫描长度,直到找到您想要的 x-value。

const x = 100; // known x-value
const path = document.getElementById('Timeline---Deactivated');
const pathLength = path.getTotalLength();
const range = [0, pathLength];
let guess, result;
for( let iterations = 0; iterations < 11; iterations++) {
    guess = (range[0]+range[1])/2;
    result = path.getPointAtLength(guess);
    if( result.x < x) {
        // target is to the right
        range[0] = guess;
    }
    else range[1] = guess;
}
return result; // SVGPoint with result.x and result.y

理想的迭代次数基于X值的可能范围。在您的情况下,路径结束于 (1417,164),因此迭代应该转到 ceil(log_2(1417)),即 11。如果您有更大的图形,您可能需要将其设置为 12,或者您可以只需将其设置为 20 或其他值即可。并不是说需要更多的步骤才能保持高精度结果。