Skip to content
Go back

canvas画布上橡皮擦效果的实现

原生canvas画布橡皮擦效果的实现

方式一: 增加绘制白色线条

canvas-eraser

实现方式主要是擦除时不断地给画布新增绘制橡皮擦颜色(白色)来达到效果:

        // 鼠标移动时绘制
        canvas.addEventListener('mousemove', (e) => {
            if (!drawing) return;

            const [x, y] = getMousePos(e);

            ctx.lineWidth = 5;
            ctx.lineCap = 'round';
            ctx.strokeStyle = erasing ? 'white' : 'black'; // 如果在擦除,使用白色

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();
            ctx.closePath();

方式二: 使用globalCompositeOperation 属性


            if (!erasing) {
                // 绘制模式
                context.globalCompositeOperation = 'source-over'; // 正常绘制
                context.lineWidth = 5;
                context.lineCap = 'round';
                context.strokeStyle = 'black';

                context.beginPath();
                context.moveTo(lastX, lastY);
                context.lineTo(x, y);
                context.stroke();
                context.closePath();
            } else {
                // 橡皮擦模式
                context.globalCompositeOperation = 'destination-out'; // 擦除模式
                context.lineWidth = 20; // 橡皮擦宽度

                context.beginPath();
                context.moveTo(lastX, lastY);
                context.lineTo(x, y);
                context.stroke();
                context.closePath();
            }

fabric和konva橡皮擦的使用

fabricjs

https://fabric5.fabricjs.com/erasing fabricjs擦除是对整个对象的擦除,并且可能存在deep的情况,嵌套对象的深层擦除

konvajs

https://konvajs.org/docs/sandbox/Free_Drawing.html 和fabric类似,仍然是追加绘制内容来产生橡皮擦效果

其他问题


Share this post on:

Next Post
一首英文诗