Add erase ink functionality in HTML5 canvas whiteboard

423 views Asked by At

I have created a HTML5 canvas whiteboard which can be used to write anything using mouse.I had tried to add the eraser functionality to the whiteboard which will erase pixels from the screen, but it is not working. I am sharing the relevant portions of code

function drawOnCanvas() {
var canvas = document.querySelector('#board');
this.ctx = canvas.getContext('2d');
var ctx = this.ctx;

var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));

var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};

/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
    last_mouse.x = mouse.x;
    last_mouse.y = mouse.y;

    mouse.x = e.pageX - this.offsetLeft;
    mouse.y = e.pageY - this.offsetTop;
}, false);


/* Drawing on Paint App */
ctx.lineWidth = (writeMode===1)?5:8;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
setTimeout(()=>{
  ctx.strokeStyle = (writeMode===1)?'blue':'white';  //choose pen or eraser (pen is 1 and eraser is 0)
},100)

canvas.addEventListener('mousedown', function(e) {
    canvas.addEventListener('mousemove', onPaint, false);
}, false);

canvas.addEventListener('mouseup', function() {
    canvas.removeEventListener('mousemove', onPaint, false);
}, false);

var root = this;
var onPaint = function() {
    ctx.beginPath();
    ctx.moveTo(last_mouse.x, last_mouse.y);
    ctx.lineTo(mouse.x, mouse.y);
    ctx.closePath();
    ctx.stroke();
};

}

Please help me to add the eraser feature in the existing code

2

There are 2 answers

3
Hermanboxcar On BEST ANSWER

Try using a brush the same color as the background color of the canvas. It will look like erasing, but it's like putting white-out on white paper.

sugs on your code: use let instead of var for onPaint, do function onPaint() {...} instead.

0
Parthik Kumar Das On

You can paint it the same colour as background but you can also make a eraser by using clearRect ctx.clearRect(mouse.x, mouse.y, 10, 10) it will create a eraser of 10 by 10 size