美文网首页
canvas 实现橡皮擦

canvas 实现橡皮擦

作者: 康乐芳华 | 来源:发表于2021-03-04 15:33 被阅读0次

canvas 实现橡皮擦

<div class="canvas-wrapper">
  <canvas id="canvas" width="800" height="800">a canvas</canvas>
</div>
 * {
      box-sizing: border-box;
      margin: 0;
    }

    #canvas {
      box-shadow: 0 0 0 1px tomato;
      padding: 0px;
      transform: scale(0.5);
      transform-origin: top left;
    }

    .canvas-wrapper {
      width: 400px;
      height: 400px;
    }
const canvas_con = canvas.getContext("2d");
let darwingSurfaceImageData = null;
let isErasing = false;

canvas_con.fillStyle = "rgba(200, 10, 50, .1)";
canvas_con.strokeStyle = "rgba(200, 10, 50, .8)";

canvas_con.beginPath();
canvas_con.save();
canvas_con.translate(canvas.width / 2, canvas.height / 2);
const part = 17;
const unitAngle = (Math.PI * 2) / part;
for (let i = 0; i < part; i++) {
    canvas_con.save();
    canvas_con.rotate(unitAngle * i);
    canvas_con.fillRect(0, -canvas.width / 16, canvas.width / 5, canvas.width / 8);
    canvas_con.restore();
}
canvas_con.restore();
canvas_con.closePath();

function saveDrawingSfarce() {
    darwingSurfaceImageData = canvas_con.getImageData(
        0,
        0,
        canvas.width,
        canvas.height
    );
}

saveDrawingSfarce();
function restoreDrawingSface() {
    canvas_con.putImageData(darwingSurfaceImageData, 0, 0);
}
function drawEraser({ x, y }) {
    canvas_con.save();
    canvas_con.beginPath();
    canvas_con.arc(x, y, 10, 0, Math.PI * 2, false);
    canvas_con.clip();
    canvas_con.clearRect(0, 0, canvas.width, canvas.height);
    canvas_con.closePath();
    canvas_con.restore();
}

canvas.onmousedown = function (e) {
    if (e.button !== 0) {
        return;
    }
    isErasing = true;
    drawEraser({
        x: e.x * 2,
        y: e.y * 2
    });
};

canvas.onmouseup = function (e) {
    isErasing = false;
    saveDrawingSfarce();
    restoreDrawingSface();
};

canvas.onmousemove = function (e) {
    if (e.button !== 0) {
        return;
    }
    if (isErasing) {
        drawEraser({
            x: e.x * 2,
            y: e.y * 2
        });
    }
};


相关文章

网友评论

      本文标题:canvas 实现橡皮擦

      本文链接:https://www.haomeiwen.com/subject/kcjkqltx.html