Skip to content

Instantly share code, notes, and snippets.

@beardicus
Last active March 19, 2024 21:44
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beardicus/8cbe9511d43e3fb58d76e336f76f4eb2 to your computer and use it in GitHub Desktop.
Save beardicus/8cbe9511d43e3fb58d76e336f76f4eb2 to your computer and use it in GitHub Desktop.
Paper.js Vector Erase
license: mit
border: yes
height: 640

What is This?

This sketch shows a way to implement a vector eraser with Paper.js. Draw a doodle, switch to the erase tool, and erase away. Your artwork will be masked in real-time while you are erasing, then when you let go of the mouse button the actual vector subtraction operations will be performed.

How Does it Work?

The eraser tool draws a normal path. With some blend mode magic – which I discovered here – it is possible to mask a select group of items, leaving the rest of the document unaffected. This allows us to give the illusion that the eraser path is actually erasing, revealing whatever is in the background. Because it's using native canvas blend modes it's very responsive while erasing.

On onMouseUp, the eraser path is outlined using offsetting routines found in offset.js. The offset paths are combined to make a closed shape, then all overlaps are removed and the outline is simplified again. This shape is then subtracted from any of the targeted drawing paths it overlaps with.

<!DOCTYPE html>
<meta charset="UTF-8">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body,
html {
height: 100%;
}
#canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
<canvas id="canvas"></canvas>
<script type="text/javascript">
window.onload = function() {
paper.install(window)
paper.setup(document.getElementById('canvas'))
// set up some options and the dat.gui panel
var options = {
drawWidth: 10,
eraseWidth: 50,
drawColor: '#000000',
toolSelect: 'draw',
clearCanvas: function() {
topLayer.removeChildren()
}
}
var gui = new dat.GUI()
gui.addColor(options, 'drawColor')
gui.add(options, 'drawWidth', 5, 50)
gui.add(options, 'eraseWidth', 1, 100)
gui.add(options, 'toolSelect', ['draw', 'erase']).onChange(function(value) {
if (value === 'erase') {
eraseTool.activate()
} else {
drawTool.activate()
}
})
gui.add(options, 'clearCanvas')
// this layer holds the background pattern
var bottomLayer = new Layer()
var cols = 10,
viewport = project.view.bounds,
colWidth = viewport.width / cols,
colHeight = viewport.height
for (var i = 0; i < cols; i++) {
new Path.Rectangle({
point: [i * 2 * colWidth, 0],
size: [colWidth, colHeight],
fillColor: '#eee'
})
}
// new layer for drawing and erasing on
var topLayer = new Layer()
// tool for drawing simple strokes on topLayer
var drawTool = new Tool()
drawTool.minDistance = 5
drawTool.onMouseDown = function(event) {
drawPath = new Path({
strokeColor: options.drawColor,
strokeWidth: options.drawWidth * view.pixelRatio,
strokeCap: 'round',
strokeJoin: 'round'
})
}
drawTool.onMouseDrag = function(event) {
drawPath.add(event.point)
}
drawTool.onMouseUp = function(event) {
drawPath.selected = true
}
// tool that 'erases' within the active layer only. first it simulates erasing
// using a stroked path and blend modes while you draw. onMouseUp it converts
// the toolpath to a shape and uses that to path.subtract() from each path
var eraseTool = new Tool()
eraseTool.minDistance = 10
var path, tmpGroup, mask
eraseTool.onMouseDown = function(event) {
// TODO: deal w/ noop when activeLayer has no children
// right now we just draw in white
// create the path object that will record the toolpath
path = new Path({
strokeWidth: options.eraseWidth * view.pixelRatio,
strokeCap: 'round',
strokeJoin: 'round',
strokeColor: 'white'
})
// learned about this blend stuff from this issue on the paperjs repo:
// https://github.com/paperjs/paper.js/issues/1313
// move everything on the active layer into a group with 'source-out' blend
tmpGroup = new Group({
children: topLayer.removeChildren(),
blendMode: 'source-out',
insert: false
})
// combine the path and group in another group with a blend of 'source-over'
mask = new Group({
children: [path, tmpGroup],
blendMode: 'source-over'
})
}
eraseTool.onMouseDrag = function(event) {
// onMouseDrag simply adds points to the path
path.add(event.point)
}
eraseTool.onMouseUp = function(event) {
// simplify the path first, to make the following perform better
path.simplify()
var eraseRadius = (options.eraseWidth * view.pixelRatio) / 2
// find the offset path on each side of the line
// this uses routines in the offset.js file
var outerPath = OffsetUtils.offsetPath(path, eraseRadius)
var innerPath = OffsetUtils.offsetPath(path, -eraseRadius)
path.remove() // done w/ this now
outerPath.insert = false
innerPath.insert = false
innerPath.reverse() // reverse one path so we can combine them end-to-end
// create a new path and connect the two offset paths into one shape
var deleteShape = new Path({
closed: true,
insert: false
})
deleteShape.addSegments(outerPath.segments)
deleteShape.addSegments(innerPath.segments)
// create round endcaps for the shape
// as they aren't included in the offset paths
var endCaps = new CompoundPath({
children: [
new Path.Circle({
center: path.firstSegment.point,
radius: eraseRadius
}),
new Path.Circle({
center: path.lastSegment.point,
radius: eraseRadius
})
],
insert: false
})
// unite the shape with the endcaps
// this also removes all overlaps from the stroke
deleteShape = deleteShape.unite(endCaps)
deleteShape.simplify()
// grab all the items from the tmpGroup in the mask group
var items = tmpGroup.getItems({ overlapping: deleteShape.bounds })
items.forEach(function(item) {
var result = item.subtract(deleteShape, {
trace: false,
insert: false
}) // probably need to detect closed vs open path and tweak these settings
if (result.children) {
// if result is compoundShape, yoink the individual paths out
item.parent.insertChildren(item.index, result.removeChildren())
item.remove()
} else {
if (result.length === 0) {
// a fully erased path will still return a 0-length path object
item.remove()
} else {
item.replaceWith(result)
}
}
})
topLayer.addChildren(tmpGroup.removeChildren())
mask.remove()
}
}
</script>
<script type="text/javascript" src="https://unpkg.com/paper@0.11.5/dist/paper-full.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.3/dat.gui.min.js"></script>
<script type="text/javascript" src="offset.js"></script>
/*
Copyright (c) 2014-2017, Jan Bösenberg & Jürg Lehni
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var OffsetUtils = {
offsetPath: function(path, offset, result) {
var outerPath = new Path({ insert: false }),
epsilon = Numerical.GEOMETRIC_EPSILON,
enforeArcs = true;
for (var i = 0; i < path.curves.length; i++) {
var curve = path.curves[i];
if (curve.hasLength(epsilon)) {
var segments = this.getOffsetSegments(curve, offset),
start = segments[0];
if (outerPath.isEmpty()) {
outerPath.addSegments(segments);
} else {
var lastCurve = outerPath.lastCurve;
if (!lastCurve.point2.isClose(start.point, epsilon)) {
if (enforeArcs || lastCurve.getTangentAtTime(1).dot(start.point.subtract(curve.point1)) >= 0) {
this.addRoundJoin(outerPath, start.point, curve.point1, Math.abs(offset));
} else {
// Connect points with a line
outerPath.lineTo(start.point);
}
}
outerPath.lastSegment.handleOut = start.handleOut;
outerPath.addSegments(segments.slice(1));
}
}
}
if (path.isClosed()) {
if (!outerPath.lastSegment.point.isClose(outerPath.firstSegment.point, epsilon) && (enforeArcs ||
outerPath.lastCurve.getTangentAtTime(1).dot(outerPath.firstSegment.point.subtract(path.firstSegment.point)) >= 0)) {
this.addRoundJoin(outerPath, outerPath.firstSegment.point, path.firstSegment.point, Math.abs(offset));
}
outerPath.closePath();
}
return outerPath;
},
/**
* Creates an offset for the specified curve and returns the segments of
* that offset path.
*
* @param {Curve} curve the curve to be offset
* @param {Number} offset the offset distance
* @returns {Segment[]} an array of segments describing the offset path
*/
getOffsetSegments: function(curve, offset) {
if (curve.isStraight()) {
var n = curve.getNormalAtTime(0.5).multiply(offset),
p1 = curve.point1.add(n),
p2 = curve.point2.add(n);
return [new Segment(p1), new Segment(p2)];
} else {
var curves = this.splitCurveForOffseting(curve),
segments = [];
for (var i = 0, l = curves.length; i < l; i++) {
var offsetCurves = this.getOffsetCurves(curves[i], offset, 0),
prevSegment;
for (var j = 0, m = offsetCurves.length; j < m; j++) {
var curve = offsetCurves[j],
segment = curve.segment1;
if (prevSegment) {
prevSegment.handleOut = segment.handleOut;
} else {
segments.push(segment);
}
segments.push(prevSegment = curve.segment2);
}
}
return segments;
}
},
/**
* Approach for Curve Offsetting based on:
* "A New Shape Control and Classification for Cubic Bézier Curves"
* Shi-Nine Yang and Ming-Liang Huang
*/
offsetCurve_middle: function(curve, offset) {
var v = curve.getValues(),
p1 = curve.point1.add(Curve.getNormal(v, 0).multiply(offset)),
p2 = curve.point2.add(Curve.getNormal(v, 1).multiply(offset)),
pt = Curve.getPoint(v, 0.5).add(
Curve.getNormal(v, 0.5).multiply(offset)),
t1 = Curve.getTangent(v, 0),
t2 = Curve.getTangent(v, 1),
div = t1.cross(t2) * 3 / 4,
d = pt.multiply(2).subtract(p1.add(p2)),
a = d.cross(t2) / div,
b = d.cross(t1) / div;
return new Curve(p1, t1.multiply(a), t2.multiply(-b), p2);
},
offsetCurve_average: function(curve, offset) {
var v = curve.getValues(),
p1 = curve.point1.add(Curve.getNormal(v, 0).multiply(offset)),
p2 = curve.point2.add(Curve.getNormal(v, 1).multiply(offset)),
t = this.getAverageTangentTime(v),
u = 1 - t,
pt = Curve.getPoint(v, t).add(
Curve.getNormal(v, t).multiply(offset)),
t1 = Curve.getTangent(v, 0),
t2 = Curve.getTangent(v, 1),
div = t1.cross(t2) * 3 * t * u,
v = pt.subtract(
p1.multiply(u * u * (1 + 2 * t)).add(
p2.multiply(t * t * (3 - 2 * t)))),
a = v.cross(t2) / (div * u),
b = v.cross(t1) / (div * t);
return new Curve(p1, t1.multiply(a), t2.multiply(-b), p2);
},
/**
* This algorithm simply scales the curve so its end points are at the
* calculated offsets of the original end points.
*/
offsetCurve_simple: function (crv, dist) {
// calculate end points of offset curve
var p1 = crv.point1.add(crv.getNormalAtTime(0).multiply(dist));
var p4 = crv.point2.add(crv.getNormalAtTime(1).multiply(dist));
// get scale ratio
var pointDist = crv.point1.getDistance(crv.point2);
// TODO: Handle cases when pointDist == 0
var f = p1.getDistance(p4) / pointDist;
if (crv.point2.subtract(crv.point1).dot(p4.subtract(p1)) < 0) {
f = -f; // probably more correct than connecting with line
}
// Scale handles and generate offset curve
return new Curve(p1, crv.handle1.multiply(f), crv.handle2.multiply(f), p4);
},
getOffsetCurves: function(curve, offset, method) {
var errorThreshold = 0.01,
radius = Math.abs(offset),
offsetMethod = this['offsetCurve_' + (method || 'middle')],
that = this;
function offsetCurce(curve, curves, recursion) {
var offsetCurve = offsetMethod.call(that, curve, offset),
cv = curve.getValues(),
ov = offsetCurve.getValues(),
count = 16,
error = 0;
for (var i = 1; i < count; i++) {
var t = i / count,
p = Curve.getPoint(cv, t),
n = Curve.getNormal(cv, t),
roots = Curve.getCurveLineIntersections(ov, p.x, p.y, n.x, n.y),
dist = 2 * radius;
for (var j = 0, l = roots.length; j < l; j++) {
var d = Curve.getPoint(ov, roots[j]).getDistance(p);
if (d < dist)
dist = d;
}
var err = Math.abs(radius - dist);
if (err > error)
error = err;
}
if (error > errorThreshold && recursion++ < 8) {
if (error === radius) {
// console.log(cv);
}
var curve2 = curve.divideAtTime(that.getAverageTangentTime(cv));
offsetCurce(curve, curves, recursion);
offsetCurce(curve2, curves, recursion);
} else {
curves.push(offsetCurve);
}
return curves;
}
return offsetCurce(curve, [], 0);
},
/**
* Split curve into sections that can then be treated individually by an
* offset algorithm.
*/
splitCurveForOffseting: function(curve) {
var curves = [curve.clone()], // Clone so path is not modified.
that = this;
if (curve.isStraight())
return curves;
function splitAtRoots(index, roots) {
for (var i = 0, prevT, l = roots && roots.length; i < l; i++) {
var t = roots[i],
curve = curves[index].divideAtTime(
// Renormalize curve-time for multiple roots:
i ? (t - prevT) / (1 - prevT) : t);
prevT = t;
if (curve)
curves.splice(++index, 0, curve);
}
}
// Recursively splits the specified curve if the angle between the two
// handles is too large (we use 60° as a threshold).
function splitLargeAngles(index, recursion) {
var curve = curves[index],
v = curve.getValues(),
n1 = Curve.getNormal(v, 0),
n2 = Curve.getNormal(v, 1).negate(),
cos = n1.dot(n2);
if (cos > -0.5 && ++recursion < 4) {
curves.splice(index + 1, 0,
curve.divideAtTime(that.getAverageTangentTime(v)));
splitLargeAngles(index + 1, recursion);
splitLargeAngles(index, recursion);
}
}
// Split curves at cusps and inflection points.
var info = curve.classify();
if (info.roots && info.type !== 'loop') {
splitAtRoots(0, info.roots);
}
// Split sub-curves at peaks.
for (var i = curves.length - 1; i >= 0; i--) {
splitAtRoots(i, Curve.getPeaks(curves[i].getValues()));
}
// Split sub-curves with too large angle between handles.
for (var i = curves.length - 1; i >= 0; i--) {
//splitLargeAngles(i, 0);
}
return curves;
},
/**
* Returns the first curve-time where the curve has its tangent in the same
* direction as the average of the tangents at its beginning and end.
*/
getAverageTangentTime: function(v) {
var tan = Curve.getTangent(v, 0).add(Curve.getTangent(v, 1)),
tx = tan.x,
ty = tan.y,
abs = Math.abs,
flip = abs(ty) < abs(tx),
s = flip ? ty / tx : tx / ty,
ia = flip ? 1 : 0, // the abscissa index
io = ia ^ 1, // the ordinate index
a0 = v[ia + 0], o0 = v[io + 0],
a1 = v[ia + 2], o1 = v[io + 2],
a2 = v[ia + 4], o2 = v[io + 4],
a3 = v[ia + 6], o3 = v[io + 6],
aA = -a0 + 3 * a1 - 3 * a2 + a3,
aB = 3 * a0 - 6 * a1 + 3 * a2,
aC = -3 * a0 + 3 * a1,
oA = -o0 + 3 * o1 - 3 * o2 + o3,
oB = 3 * o0 - 6 * o1 + 3 * o2,
oC = -3 * o0 + 3 * o1,
roots = [],
epsilon = Numerical.CURVETIME_EPSILON,
count = Numerical.solveQuadratic(
3 * (aA - s * oA),
2 * (aB - s * oB),
aC - s * oC, roots,
epsilon, 1 - epsilon);
// Fall back to 0.5, so we always have a place to split...
return count > 0 ? roots[0] : 0.5;
},
addRoundJoin: function(path, dest, center, radius) {
// return path.lineTo(dest);
var middle = path.lastSegment.point.add(dest).divide(2),
through = center.add(middle.subtract(center).normalize(radius));
path.arcTo(through, dest);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment