<!DOCTYPE html>
<html>
<head>
<title>刮刮卡</title>
<meta name="viewport" content="width=device-width"/>
<style type="text/css">
#canvas1{
background: url(https://img-my.csdn.net/uploads/201506/11/1434025119_9005.jpg) no-repeat;
background-size: 100% 100%;
background-position: center;
}
button{
width: 100px;
height: 44px;
margin-top: 50px;
}
</style>
</head>
<body>
<canvas id="canvas1" width="250px" height="100px"></canvas>
<button id="clear">Clear</button>
<script>
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d'),
width = 250,
height = 100,
radius = 10,
lineWidth = radius*2;
var ol = canvas.offsetLeft,
ot = canvas.offsetTop;
function fill(reveal){
ctx.beginPath();
if(reveal !== true){
ctx.globalCompositeOperation = 'source-over';
}
ctx.fillStyle = '#ccc';
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeOperation = 'destination-out';
};
fill();
ctx.lineCap = 'round';
ctx.lineWidth = lineWidth;
ctx.lineJoin = 'round';
canvas.addEventListener('touchmove',function(e){
var touch = e.touches[0];
var x = touch.clientX - ol, y = touch.clientY - ot;
ctx.lineTo(x,y);
ctx.stroke();
});
canvas.addEventListener('touchend',function(e){
var data = ctx.getImageData(0,0,width,height).data;
for(var i=0,j=0;i< data.length;i+=4){
if(data[i] && data[i+1] && data[i+2] && data[i+3]){
j++;
}
//console.log(data[i] +','+ data[i+1] +','+ data[i+2] +','+ data[i+3]);
}
if(j <= width * height * 0.5){
alert('ok');
fill(true);
}
});
document.querySelector('#clear').addEventListener('click',fill);
document.body.addEventListener('touchmove',function(e){
e.preventDefault();
});
</script>
</body>
</html>
【html5】Canvas 刮刮卡
最新推荐文章于 2019-12-27 10:31:59 发布