I want to implement eraser in my web app using Fabric.js. Is there any way to implement eraser in Fabric.js? For example, such as in MS Paint?
相关问题
- Does using percentages instead of pixels change an
- Method for drawing circles in a pyramid pattern
- character width calculation wrong with some font w
- HTML5 - Canvas - Optimization for large images
- fabric.js straight line and select on click
相关文章
- canvas.toDataURL() not working properly [duplicate
- Drawing a filled circle in a canvas on mouseclick
- How to destroy / reload the canvas in html 5?
- Some Android devices extremely slow when rendering
- HTML5 Canvas: How to border a fillRect?
- Canvas to blob on Edge
- Most concise way to assign a value from a variable
- Html over the Canvas?
I just wrote my eraser in Fabric, and I hope to be able answer also the questions made by @kangax.
First, if you want to have a handwriting eraser, you should build an object like this:
Then I slightly hacked the actual fabric library (v. 2.4.3) here:
Using
globalCompositeOperation
you can manage yourcanvas.freeDrawingBrush
to draw a colored path (the color you wish, I choose red, but you can also choose the background color of your canvas) as this:So, when you move your mouse onto the canvas, you'll see a red path. When you move up the mouse, the path is finally created and the gCO is applied, erasing everything down the red path.
Well, if you want to save the canvas, I prefer to use the
canvas.toSVG()
function (it's great for retina screens if you're able to manage it). So, to save the canvas as SVG you just need this linecanvas.toSVG()
and you can store the result somewhere. When you want to restore the canvas, you should manage also the 'erasure' id, so you can use my restore function:I hope to be useful for everybody having headaches with Fabric.js
EDIT: as suggested by @Benni the lines related to the erasure can be displaced. If you want to fix them onto the canvas, you might slightly change the code using lockMovementX and lockMovementY. So, in the fabric.js lib, after
add:
Then, in your code, after
canvas.freeDrawingBrush.id = 'erasure';
add:There's no built-in eraser in Fabric and implementing is a bit difficult.
The thing about Fabric is that everything is object-based and most of the things are also vector-based.
Unlike with native canvas, we can't just erase some pixels on a global bitmap. We have entire object model underneath, and canvas output is a simple loop of all those objects rendered onto canvas.
One way we could emulate eraser is perhaps by having some kind of overlay on top of canvas. And sort-of draw "erased" lines on it, giving illusion of underlying objects being wiped out.
But there are still complications with this:
There's likely more issues that I didn't think of at the moment.