Boolean Operations in SVG Using Javascript

Publish in Javascript el 21/05/2025 00:51

Boolean Operations Between SVG Shapes Using Clipper.js: A Technical Approach


Introduction

Boolean operations between vector shapes are a fundamental feature in graphic editors and design tools. These operations allow you to combine, subtract, or intersect shapes to create more complex compositions. A common way to implement these operations is through the Clipper.js library, which, although not specifically designed to work with SVG, can be adapted to achieve effective results.

This article explains the technical process behind performing Boolean operations between SVG shapes using Clipper.js, from extracting the d attribute from a path to generating a new SVG element based on the result of the operation.


Why isn’t Clipper.js designed to work directly with SVG?

Clipper.js is a polygon clipping library that operates on geometric data structures in the form of arrays of coordinates {X: x, Y: y}. It"s not DOM-oriented or targeted at specific formats like SVG, so any interaction with SVG elements must first be translated into a format Clipper understands.

This means that if we want to use Clipper.js in an SVG environment, we must:

  • Convert the SVG paths to arrays of points.
  • Perform the Boolean operations.
  • Convert the result back to a valid SVG path.


Input structure expected by Clipper.js

Clipper expects to receive contours as arrays of coordinates in the format {X: x, Y: y} , where each array represents a closed path. For example:

This format allows performing Boolean operations between two sets of polygons (e.g., "Subject" and "Clip").


Only Paths Can Be Used in SVG

SVG supports multiple types of graphic elements (<rect>, <circle>, <polygon>, etc.), but only <path> elements have a d attribute that defines their complete geometry. This means that any SVG shape other than a path must first be converted to a path before Boolean operations can be applied to it.


Play Code


Why is it important to remove transformations before using Clipper.js?

Clipper does not directly understand or process transform attributes (such as translate, rotate, scale, etc.). If an SVG element has a transformation applied:

Its position or shape on the screen does not reflect its original definition in the d attribute.

This causes the extracted points to not represent the actual geometry displayed, leading to incorrect or unexpected results when performing Boolean operations.

Solution: "Flatten" or apply transformations to the path

The process consists of applying geometric transformations directly to the path points, removing the transform attribute from the DOM. This way, the path has updated coordinates that reflect how it actually appears on screen.


Extracting and converting the d attribute to Clipper format

The d attribute of a <path> contains SVG commands (such as M, L, C, Z) followed by coordinates. To use them in Clipper, we must parse these commands and generate a list of coordinates (x, y).

Conversion example:

Given a d="M100,100 L150,100 L150,150 Z":

  • We parse the commands and extract the coordinates.
  • We convert them to an array of appropriately scaled {X: x, Y: y} objects.

This process is performed in the getClipperPath(id) function in the provided code.


Generating the SVG result from Clipper’s output

Once the Boolean operation (either UNION, INTERSECTION, DIFFERENCE, or XOR) is performed, Clipper returns an array of point arrays representing the resulting paths.

To integrate this result into the SVG DOM, we need to:

  • Scale the points back to real-world coordinates.
  • Clean up and simplify redundant points.
  • Convert the points into a valid string for a <path>.

This is done in the paths2string(solution_paths, scale) function in the code.

Example output:


This new path is added to the SVG as a preview of the result of the Boolean operation.


Bézier Curve Sampling for Accuracy

A simple rectangle has only 4 points, but Clipper requires many more to correctly calculate intersections and junctions between complex shapes (especially when there are curves).

Strategy Used:

The getPointAtLength() method is used to sample n points along the path, even on curved segments (C). This ensures that Clipper has sufficient resolution to process shapes with high accuracy.


The step variable controls the sampling density. A lower value produces greater accuracy, but also increases the computational load.


Cleanup and Optimization of the Final Path

Clipper°s output often includes many redundant points, especially after operations on curved shapes. Ideally, these should be cleaned up to obtain an efficient and legible SVG path.

However, this functionality is not fully implemented in the current code, although basic cleanup is applied with:


However, there is still room for improvement in the final result, such as detecting collinearity and removing unnecessary points.


Conclusion

Performing Boolean operations between SVG shapes using Clipper.js is a technical and detailed process that involves:

  • Converting SVG shapes to paths.
  • Accurate point sampling to faithfully represent the shapes.
  • Interfacing with Clipper.js to perform Boolean operations.
  • Generating new SVG elements from the output.

This approach allows developers to build advanced graphical editors with features such as union, intersection, difference, and XOR between vector shapes.

While the process is technically complex, the result is a powerful tool that greatly expands SVG editing capabilities in the browser.


Additional Resources

Clipper.js GitHub

SVG Path Specification - MDN Web Docs

getPathData() API - Useful tool for parsing SVG files


También te puede interesar

Handling Clicks, MouseOver, and MouseLeave on SVG elements with Javascript
Handling Clicks, MouseOver, and MouseLeave on SVG elements with Javascript

In today’s web development landscape, Scalable Vector Graphics (SVG) play a crucial role in creat...

How to Export SVG as PNG or JPEG with JavaScript
How to Export SVG as PNG or JPEG with JavaScript

Today I want to share with you a handy web tool I created for converting SVG images to PNG format...

Edit and Change SVG Colors with Javascript
Edit and Change SVG Colors with Javascript

Customizing SVG Elements: A Deep Dive into Our New Color Editor ToolAs a web developer and educat...

How do Transforms work in SVG?
How do Transforms work in SVG?

Types of Transformations in SVG: A Complete Technical GuideThe transform attribute in SVG (Scalab...

Javascript CSS Gradient Generator
Javascript CSS Gradient Generator

Inside the Gradient Generator Tool of ArtDraw: How It WorksHi everyone, I"m the developer behind ...

Color Palette Generator in Javascript
Color Palette Generator in Javascript

As someone passionate about design and front-end development, I’ve always been fascinated by how ...