您的位置:首页 > Web前端 > HTML5

【html5】Canvas 刮刮卡

2015-06-11 20:14 633 查看
<!DOCTYPE html>
<html>
<head>
<title>刮刮卡</title>
<meta name="viewport" content="width=device-width"/>
<style type="text/css">
#canvas1{
background: url(http://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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: