简体   繁体   中英

SVG - get the difference path of two paths

Is there an easy way to get the difference path of two SVG paths? I have a large polygon where I need to cut some holes from or which I have to cut into pieces by subtracting a path.

Preferably something in JavaScript, but C# would also work.

I've already searched for solutions. The closest is How can I cut one shape from another , but it is about shapes, not paths. And this answer gives just a clue how to draw a path with holes but no way to automate this.

Am I really stuck with manually adding the second path (including all the stuff like checking the direction, absolute/relative position, transforms etc)?

I'm not very sure, what you want to achieve, but I can see two possibilities: A) draw a polygon with holes or B) make boolean difference operation between two polygons.

A) DRAW POLYGON WITH HOLES

The winding order is the key. If you have outer polygon (SVG path), which is clockwise (CW) like this:

"M155,61.67 L155,212.7 L288.98,212.7 L288.98,61.67 L173.01999999999998,61.67 L155,61.67Z"

and a hole polygon (SVG path) which is counter-clockwise (CCW), like this: "M274.37,190.77 L171.24,190.77 L171.24,81.16 L274.37,81.16 L274.37,81.16 L274.37,190.77Z"

And you combine these into same path:

"M155,61.67 L155,212.7 L288.98,212.7 L288.98,61.67 L173.01999999999998,61.67 L155,61.67ZM274.37,190.77 L171.24,190.77 L171.24,81.16 L274.37,81.16 L274.37,81.16 L274.37,190.77Z"

you get the following polygon with hole:

在此输入图像描述

In the above image it seems that inner polygon is subtracted from the outer polygon.

B) MAKE BOOLEAN DIFFERENCE OPERATION BETWEEN TWO POLYGONS

If you want to cut one polygon from other polygon and want to create a new geometry by making a boolean difference operation between two or more polygons, you can use JAVASCRIPT CLIPPER , which has AN ONLINE DEMO , where you can play with different boolean operations. You can also input your own polygons by clicking Polygons - Custom. You can input them using SVG path syntax (only MoveTo:s and LineTo:s are permitted). There is also a Polygon Explorer, where you can see the result of operations. Also outputs can be seen as SVG paths. There is also A WIKI PAGE , which has code examples.

An example of Subject ("polygon") and Clip ("clipping") polygons: 在此输入图像描述

Boolean Difference between Subject and Clip polygons: 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM