canvas–刮刮乐效果,常见于电商网站的刮奖环节
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<title>Title</title>
<style>
body{
-moz-user-select: none;
-webkit-user-select: none;
position: relative;
}
#cav1,#cav2{
border: 1px solid red;
position: absolute;
}
</style>
</head>
<body>
<canvas id="cav1" width="400" height="300"></canvas>
<canvas id="cav2" width="400" height="300"></canvas>
<script>
var cav1 = document.getElementById('cav1');
var cav2 = document.getElementById('cav2');
var cax1 = cav1.getContext('2d');
var cax2 = cav2.getContext('2d');
cax1.font = ('100px 微软雅黑');
cax1.fillText('哈哈哈',50,150);
cax2.fillStyle = '#ddd';
cax2.fillRect(0,0,400,300);
cax2.fill();
cax2.globalCompositeOperation = 'destination-out';
var offsetX = cav2.offsetLeft;
var offsetY = cav2.offsetTop;
var mousedown = false;
function eventDown(e){
e.preventDefault();
mousedown = true;
}
function eventUp(e){
e.preventDefault();
mousedown = false;
}
//touches是当前屏幕上所有触摸点的列表;
//targetTouches是当前对象上所有触摸点的列表;
//changedTouches是涉及当前事件的触摸点的列表。
function eventMove(e){
e.preventDefault();
if(mousedown){
if(e.changedTouches){
e=e.changedTouches[e.changedTouches.length-1];
}
var x = (e.clientX + document.body.scrollLeft) - offsetX || 0;
var y = (e.clientY + document.body.scrollTop) - offsetY || 0;
cax2.beginPath();
cax2.fillStyle = 'rgba(0,0,0,1)';
cax2.arc(x,y,20,0,2*Math.PI);
cax2.fill();
cax2.closePath();
}
}
cav2.addEventListener('touchstart', eventDown);
cav2.addEventListener('touchend', eventUp);
cav2.addEventListener('touchmove', eventMove);
cav2.addEventListener('mousedown', eventDown);
cav2.addEventListener('mouseup', eventUp);
cav2.addEventListener('mousemove', eventMove);
</script>
</body>
</html>