Use the attribute globalCompositeOperation to set the value to destination-out, and the graphics drawn later will erase the overlapping part of the graphics drawn first
Effect picture:
Ideas
1. Write a div, the content of the div is the result after scraping;
2. Set the positioning of the canvas and cover the div (it is transparent at this time);
3. Draw a rectangle on the canvas and use the color (here the default black is used), which will cover the card;
4. Set the globalCompositeOperation property to destination-out;
4. Add a mouse movement event to the canvas, draw a small circle at the position of the mouse, and the effect of erasing will be achieved
Complete code
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="GBK">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
canvas{
position: absolute;
left:200px;
border:1px solid ;
top: 10px;
cursor: pointer;
}
#guaguaka{
position:absolute;
left:200px;
width: 200px;
height: 60px;
top: 10px;
font-size: 40px;
text-align:center;
}
</style>
</head>
<body>
<div id='guaguaka'>
谢谢惠顾
</div>
<canvas id='canvas'></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas')
var W = canvas.width = 200
var H = canvas.height = 60
var ctx = canvas.getContext('2d');
draw();
function draw(){
ctx.beginPath();
//绘制一个方形,用来覆盖刮刮卡的内容
ctx.fillRect(0,0,W,H);
ctx.globalCompositeOperation='destination-out';//后绘制的图形会擦除与先绘制图形重叠的部分
}
canvas.addEventListener('mousemove',function(event){
ctx.beginPath();
//鼠标移动的地方就绘制一个小圆,因为globalCompositeOperation设定了destination-out,那这个小圆会擦除之前覆盖方形的部分区域,这样就达到了刮开的效果
ctx.arc(event.offsetX,event.offsetY,10,0,2*Math.PI);
ctx.fill();
})
</script>
</body>
</html>