js实现画布绘图、橡皮擦除、刮刮卡效果
关键节点只有两处
- pen.globalCompositeOperation = 'destination-out';
- 通过背景图片实现擦除后仍保留底层图片效果
<!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>
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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部署