I was able to use g.js
to do boolean operations on vector shapes.
Not sure about the implication of mixing these two libraries in the long term or in more complex situations. The documentation of g.js
doesn’t seem to mention creating custom Path
objects, but it looks like a typical Canvas/SVG way of drawing paths.
Another library that I know has a strong Vector capability is paper.js
http://paperjs.org/examples/path-intersections/
include the script in index.html
<script src="https://cdn.rawgit.com/nodebox/g.js/master/dist/g.min.js"></script>
sketch.js
below.
// import g.js in index.html
function setup() {
createCanvas(400, 400);
background(220)
let pathA = new g.Path()
pathA.moveTo(20, 20)
pathA.lineTo(80, 20)
pathA.lineTo(100, 80)
pathA.lineTo(60, 80)
pathA.lineTo(40, 120)
pathA.closePath()
pathA.fill = 'yellow'
pathA.draw(drawingContext)
let pathB = new g.Path()
pathB.moveTo(40, 40)
pathB.lineTo(100, 40)
pathB.lineTo(140, 60)
pathB.lineTo(10, 60)
pathB.closePath()
pathB.fill = 'orange'
pathB.draw(drawingContext)
push()
translate(150, 0)
let pathC = g.compound(pathA, pathB, 'union')
pathC.fill = 'white'
pathC.stroke = 'black'
pathC.draw(drawingContext)
pop()
push()
translate(0, 150)
let pathD = g.compound(pathA, pathB, 'difference')
pathD.fill = 'white'
pathD.stroke = 'black'
pathD.draw(drawingContext)
pop()
push()
translate(150, 150)
let pathE = g.compound(pathA, pathB, 'intersection')
pathE.fill = 'white'
pathE.stroke = 'black'
pathE.draw(drawingContext)
pop()
}
Here is the online version of the sketch above: