Home > Net >  Why does the subtraction of two SVG shapes still intersect?
Why does the subtraction of two SVG shapes still intersect?

Time:06-07

Surely shape1.subtract(shape2).intersects(shape2) should always be false?

But in my paper.js code, a path with a second path removed from it still always intersects the second path. Why is this please?

I'm trying to loop through a list of paths and subtract them all so there is no overlapping. But I can't test the remaining shapes for overlap because of this error :(

Here's a demonstration of the error:

'use strict';
window.onload = setup;
let p = null; // an alias for the paper.js global object.
let canvasWidth, canvasHeight = null;
let em = null; // relative width unit the drawing is based on


function setup()
{
    p = paper;
    const canvas = document.getElementById('canvasId');
    canvasWidth = parseInt(document.getElementById('canvasId').attributes.width.nodeValue);
    canvasHeight = parseInt(document.getElementById('canvasId').attributes.height.nodeValue);
    em = canvasWidth / 100;
    p.setup(canvas);
    drawPicture();
}

function drawPicture()
{
    const shape1 = p.Path.Circle(new p.Point(200, 200), 2*em);
    shape1.fillColor = hsb(50, 0.5, 0.5, 1);
    shape1.strokeColor = hsb(0, 0, 0, 1);

    const shape2 = p.Path.Circle(new p.Point(230, 200), 2*em);
    shape2.fillColor = hsb(100, 0.5, 0.5, 1);
    shape2.strokeColor = hsb(0, 0, 0, 1);

    console.log(`shape1 intersects shape1 ?  ${shape1.intersects(shape1)}`);
    console.log(`shape1 intersects shape2 ?  ${shape1.intersects(shape2)}`);
    console.log(`(shape1 less shape2) intersects shape2 ?  ${shape1.subtract(shape2).intersects(shape2)}`);
}

function hsb(hue = 360, saturation = 1, brightness = 0.5, alpha = 1)
{
    return new p.Color({hue: hue, saturation: saturation, brightness: brightness, alpha: alpha});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.15/paper-full.js"></script>

<body>
    <canvas id="canvasId" width="1500" height="750"></canvas>
</main>

CodePudding user response:

It depends.

Remember that the two shapes will, at least mathematically, share a border. If you have two lines that follow the exact same path, do they intersect? Mathematically at least, they share infinitely many intersection points.

But ultimately it depends on how paper.js generates the new paths. It depends on how accurate the boolean operations in Paper are. And it depends on the algorithm that paper.js uses to test intersection.

If you have called subtract() on two paths, then you'll probably just have to assume that they visually don't overlap. But to work that out code-wise, you are probably going to have to keep track yourself of which paths have been subtracted.

  • Related