Creating An Eraser For HTML5 Canvas
JavaScript
12/06/2021
There are different ways to creating an eraser. ⌫ The simplest solution you will come across is an "eraser" that matches the background color. This might give you the impression that you are erasing the content, when in fact you are simply drawing on top of it.
Of course, this method won't work with a more complex background, such as a picture. 🏙 Therefore, let me show you the recommended solution.
Removing pixels
The key to all this is the context property globalCompositeOperation
. This property dictates how the canvas behaves when new shapes are drawn. For our objective, 🎯 we are interested in setting it to destination-out
.
const context = canvas.getContext('2d')context.globalCompositeOperation = 'destination-out'
What this does is make way for any new shapes by removing existing pixels that overlap with it. More importantly, however - this new shape isn't actually drawn even if you have a color 👩🎨 set.
Creating a button
To trigger this eraser functionality at will, let's set the property through a function.
const erase = () => context.globalCompositeOperation = 'destination-out'
Afterwards, we simply attach it to an "Eraser" button's click event.
<button onclick='erase()'>Eraser</button>
Drawing again
But wait! ✋ Once erase
is triggered, the "eraser" mode will stay on until it is removed. To do that, we need to revert the property back to its default value, i.e. source-over
. The perfect time to do so is when a user changes the drawing color.
const changeColor = color => { context.strokeStyle = color context.globalCompositeOperation = 'source-over' // new}
Check out my Codepen for the eraser in action!