js实现画布绘图、橡皮擦除、刮刮卡效果

发布时间 2023-04-21 11:57:50作者: Hey,Coder!

关键节点只有两处

  1. pen.globalCompositeOperation = 'destination-out';
  2. 通过背景图片实现擦除后仍保留底层图片效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .mainCanvas{
            -moz-background-size:100% 100%; background-size:100% 100%;
        }
    </style>
  
</head>
<body>
    <canvas id="mainCanvas" width="244" height="182" class="mainCanvas" >
Your browser does not support the HTML5 canvas tag.
</canvas>
<div>

    <img src="test.png" id="testimg" style="margin-left:0px; float: left;"/>
    <canvas style="float: left; "></canvas>
</div>

<script>
    let beginDrew=false;
    let canvas=document.getElementById("mainCanvas");
    let lastX,lastY;//点击时相对画布位置
    let pen=canvas.getContext("2d");
    canvas.style.backgroundImage='URL(test.png)';

    canvas.onmousedown=function(e){
        beginDrew=true;

        lastX=e.offsetX-canvas.clientLeft;
        lastY=e.offsetY-canvas.clientTop;

        pen.moveTo(lastX,lastY);
    }
    document.getElementById("testimg").onload=function(){ 
        var img=document.getElementById("testimg");
        console.log(img)
        pen.fillRect(0,0,canvas.width,canvas.height);
    };

    canvas.onmousemove=function(e){
        if(!beginDrew){
            return;
        }

        drew(pen,e);
    }
    canvas.onmouseup=function(e){
        beginDrew=false;
    }
    canvas.onmouseout=function(e){
        beginDrew=false;
    }

    function drew(pen, e){
        pen.fillStyle="red";
        pen.strokeStyle="red";
        pen.lineWidth=10;
        pen.globalCompositeOperation = 'destination-out';
        pen.lineTo(e.offsetX,e.offsetY);
        pen.stroke();
    }
</script>
</body>
</html>