【html5】Canvas 刮刮卡

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值