H5 canvas标签制作刮刮卡,只适合移动端,PC端有小问题
记得 把图片换一换!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"></meta>
<title></title>
<style>
*{
margin:0px;padding:0px;
}
html,body{
height:100%;
overflow:hidden;
}
#wrap,ul,ul>li{
height:100%;
}
ul>li{
background:url(0.jpg);
background-size:cover;
}
canvas{
position:absolute;
left:0;
top:0;
transition:2s;
}
</style>
</head>
<body>
<div id="wrap">
<canvas></canvas>
<ul>
<li></li>
</ul>
</div>
</body>
<script>
window.function(){
var canvas=document.getElementsByTagName('canvas')[0];
canvas.width=document.documentElement.clientWidth;//canvas的宽=视口的宽
canvas.height=document.documentElement.clientHeight;//canvas的高=视口的高
//判断浏览器是不是兼容canvas
if(canvas.getContext){
var ctx=canvas.getContext('2d');
}
//用js new一个image标签;
var img=new Image();
img.src='1.jpg';
//图片加载完才能操作
img.function(){
draw();
}
function draw(){
//在canvas上画图片
ctx.drawImage(img,0,0,canvas.width,canvas.height);
ctx.stroke();
//手指接触屏幕
canvas.addEventListener('touchstart',function(ev){
ev=ev||event;
var touchC=ev.changedTouches[0];//拿第一根手指
//获取手指接触屏幕的坐标
var x=touchC.clientX-canvas.offsetLeft;
var y=touchC.clientY-canvas.offsetTop;
ctx.save();
//只留下目标超过源的部分
ctx.globalCompositeOperation='destination-out'
ctx.lineWidth=40;
ctx.lineCap="round";
ctx.lineJoin="round";
ctx.beginPath();
//只能画线,用线模拟圆
ctx.moveTo(x,y);
ctx.lineTo(x+1,y+1);
ctx.stroke();
ctx.restore();
});
//手指在屏幕上滑动
canvas.addEventListener('touchmove',function(ev){
ev=ev||event;
var touchC=ev.changedTouches[0];//拿第一根手指
//获取手指接触屏幕的坐标
var x=touchC.clientX-canvas.offsetLeft;
var y=touchC.clientY-canvas.offsetTop;
ctx.save();
ctx.globalCompositeOperation='destination-out'
ctx.lineWidth=40;
ctx.lineCap="round";
ctx.lineJoin="round";
ctx.lineTo(x+1,y+1);
ctx.stroke();
ctx.restore();
});
var flag=0;
//手指离开屏幕
canvas.addEventListener('touchend',function(){
var imgdatga=ctx.getImageData(0,0,canvas.width,canvas.height);
//拿到所有的像素
var allPx=imgdatga.width*imgdatga.height;
for(var i=0;i<allPx;i++){
if(imgdatga.data[4*i+3]==0){
flag++;
}
}
//如果划开的像素大于整个canvas的一半,就让canvas的透明度为0,让图片显示出来
if(flag>=allPx/2){
canvas.style.opacity=0;
}
//过渡执行完,透明度为0,就把canvas在页面上删除
canvas.addEventListener('transitionend',function(){
this.remove();//删除canvas
});
});
}
}
</script>
</html>
转载自原文链接, 如需删除请联系管理员。
原文链接:用H5canvas制作刮刮卡,很有趣哦,转载请注明来源!