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

关键节点只有两处

  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>
posted @   Hey,Coder!  阅读(306)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2022-04-21 rocketmq dashboard 源码配置、编译
2022-04-21 windows rocketmq部署
点击右上角即可分享
微信分享提示