简体   繁体   English

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

[英]Add erase ink functionality in HTML5 canvas whiteboard

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.我创建了一个 HTML5 canvas 白板,可用于使用鼠标书写任何内容。我曾尝试将橡皮擦功能添加到白板上,这将擦除屏幕上的像素,但它不起作用。 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请帮我在现有代码中添加橡皮擦功能

Try using a brush the same color as the background color of the canvas.尝试使用与 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.建议您的代码:使用let而不是var for onPaint ,改为使用function onPaint() {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM