原理:利用globalCompositeOperation 抠出来那个画出来的那个图像设置为透明,然后就能看到这个画布下层的图片
api: globalCompositeOperation*
属性设置要在绘制新形状时应用的合成操作的类型,其中type是用于标识要使用的合成或混合模式操作的字符串
ctx.globalCompositeOperation = type;
type的12种类型见:https://developer.mozilla.org/enUS/docs/Web/API/Canvas_API/Tutorial/Compositing
常用的:
source:源
destination:目标
source-over:(默认值):源在上面,新的图像层级比较高
source-in:只留下源与目标的重叠的部分(源的那一部分)
source-out:只留下源超过目标的部分
source-atop:砍掉源溢出的部分
destination-over:目标在上面,旧的图像层级比较高
destination-in:只留下源与目标的重叠部分(目标的那一部分)
destination-out:只留下目标和超过源的部分
destination-atop:砍掉目标溢出的部分
效果图:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
/* 继承 */
#guguka,
.images {
height: 100%;
}
#guguka>.images {
background-image: url(./Images/02.png);
background-size: 100% 100%;
}
#canvas {
position: absolute;
top: 0;
left: 0;
transition:1s;
}
</style>
</head>
<body>
<div id="guguka">
<canvas id="canvas"></canvas>
<div class="images"></div>
</div>
</body>
<script>
const canvas = document.querySelector('#canvas')
var ctx = canvas.getContext('2d')
canvas.width = document.documentElement.clientWidth
canvas.height = document.documentElement.clientHeight
var img = new Image()
img.src = 'Images/03.jpg'
img.onload = function() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
var flag =0;
canvas.addEventListener('touchstart', function(e) {
e = e || event
let Touches = e.changedTouches[0]
let x = Touches.clientX - canvas.offsetLeft
let y = Touches.clientY - canvas.offsetTop
ctx.globalCompositeOperation = "destination-out";
ctx.lineWidth = 40;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.save();
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + 1, y + 1)
ctx.stroke();
ctx.restore();
})
canvas.addEventListener('touchmove', function(e) {
e = e || event
let Touches = e.changedTouches[0]
let x = Touches.clientX - canvas.offsetLeft
let y = Touches.clientY - canvas.offsetTop
ctx.save()
ctx.lineTo(x, y)
ctx.stroke()
ctx.restore()
})
canvas.addEventListener('touchend',function(e){
var imgData = ctx.getImageData(0,0,canvas.width,canvas.height)
//拿到所有的像素点的总值
var allPx = imgData.width * imgData.height;
// 判断嘛,如果一个像素点变成透明就flag++嘛
for(var i=0;i<allPx;i++){
if(imgData.data[4*i+3]===0){
flag++;
}
// 判断嘛,当flag透明的像素点大于所有像素点的30/36的时候就将canvas的透明度设置为0嘛
if(flag>=allPx/36*30){
canvas.style.opacity=0; //然后在CSS设置个transition:1s;嘛
}
}
})
// 最后动画结束之后把canvas这个节点删除了嘛
canvas.addEventListener('transitionend',function(){
console.log(this)
this.remove();
})
}
</script>
</html>