且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从SVG路径的交叉点找到新的路径(形状)?

更新时间:2022-06-11 23:11:07

我们可以用PaperJS布尔做到这一点操作,可以使用SVG路径。

We can do it with PaperJS boolean operations, which can operate with SVG paths.

PaperJS有5种不同的布尔操作: exclude 减去联合相交除以我们将使用名为 intersect 的名称。此操作也是具有相同名称的函数,它们返回 item 对象,其函数为 exportSVG() 。它返回true SVG Path元素,它具有两个路径交集的新形状。

PaperJS has 5 different boolean operations: exclude, subtract, unite, intersect, divide and we will use one from them with the name intersect. This operations are also functions with the same name and they return item object, which has the function exportSVG(). It returns true SVG Path element, which has a new shape of both paths intersection.

示例正确的解决方案

paper.install(window);
window.onload = function()
{
    paper.setup('canvas');

    var p1 = 'M 24.379464,51.504463 23.434524,23.156249 38.742559,12.572916 c 0,0 29.860118,-9.0714281 17.00893,0.755953 -12.851191,9.82738 13.229166,19.465774 13.229166,19.465774 z',
        p2 = 'm 32.883928,0.28869028 c 0,0 -15.686011,1.51190452 -8.504463,7.18154712 7.181546,5.6696426 50.270836,30.0491076 26.458332,42.3333336 -23.8125,12.284226 47.058036,14.174107 47.058036,14.174107 z',
        path1 = new Path(p1),
        path2 = new Path(p2);

    path1.fillColor = 'rgba(255,0,0,.5)';
    path1.position = new Point(25, 25);

    path2.fillColor = 'rgba(0,255,0,.5)';
    path2.position = new Point(40, 25);
    
    var result = path2.intersect(path1);
    result.selected = true;
    result.fillColor = '#77f';

    //exportSVG() docu: http://paperjs.org/reference/item/#exportsvg
    var svgPathElement = result.exportSVG(),
        dPath = svgPathElement.getAttribute('d');
    
    document.querySelector('path').setAttribute('d', dPath);

    var output = document.querySelector('#output');
    output.innerHTML = '<pre>' + dPath + '</pre>';
    output.innerHTML += '<xmp>' + svgPathElement.outerHTML + '</xmp>';
};

table
{
    margin-left:14px;
    padding-left:14px;
    border-left:1px solid gray;
    display:inline-block
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-full.min.js"></script>

<canvas id="canvas" width="75" height="75" resize></canvas>
<table><tr><td><b>Our new shape of both paths intersection in separate SVG:</b></td></tr>
<tr><td>
    <svg width="75" height="75" viewBox="0 0 75 75">
    <path fill="rgba(0,0,255,.5)" d=""/>
    </svg>
</td></tr></table>

<div id="output"></div>

有用的链接:

  • Example PaperJS Boolean Operations: exclude, subtract, unite, intersect, divide
  • PaperJS examples
  • PaperJS Reference (documentation)