在HTML5画布白板中添加擦除墨水功能



我创建了一个HTML5画布白板,可以用来用鼠标写任何东西。我曾尝试在白板上添加橡皮擦功能,它可以擦除屏幕上的像素,但不起作用。我正在分享代码的相关部分

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();
};

}

请帮助我在现有代码中添加橡皮擦功能

尝试使用与画布背景颜色相同的画笔。这看起来像擦除,但就像在白纸上涂上白色。

代码上的建议:使用let而不是var对于onPaint,执行function onPaint() {...}相反

您可以将其绘制为与背景相同的颜色,但也可以使用clearRect制作橡皮擦ctx.clearRect(mouse.x, mouse.y, 10, 10)它将创建一个10乘10大小的橡皮擦

相关内容

  • 没有找到相关文章