canvas制作一个刮刮卡
思路整理:
1.选一张背景图片,图片上有奖品内容
2.绘画颜色区把奖品文字区域遮盖
3.消除绘制的颜色区,使其看见背景图片的文字内容。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>scratch_card</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="description" content="实现一个刮刮卡的效果" />
<meta name="keywords" content="canvas, js, dom, 动效" />
<meta name="author" content="丰林, jayfeng",jayfenglin@qq.com />
<meta name="copyright" content="www.fenglin.com" />
<meta name="robots" content="all" />
<style>
.img{
margin:0 auto;
width:640px;
position:relative;
}
#canvas{
position:absolute;
left:66px;
top:360px;
}
</style>
</head>
<body>
<div class="img">
<img src="timg.jpg" />
<canvas width="510" height="248" id="canvas"></canvas>
</div>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0,0,510,248);
//添加鼠标按下
canvas.onmousedown = function(){
//获取鼠标的位置
canvas.onmousemove = function(ev){
//oEvent.clientX是指鼠标到可视区左边框的距离
//offsetLeft:获取自己左外边框与offsetParent的左内边框的距离
var bx = ev.clientX - canvas.offsetLeft - canvas.parentNode.offsetLeft;
var by = ev.clientY - canvas.offsetTop - canvas.parentNode.offsetTop;
// 在与源图片不重叠的区域上保留目标。其他部分都变成透明的。
ctx.globalCompositeOperation = "destination-out";
//画圆
ctx.beginPath();
ctx.arc(bx,by,20,0,2*Math.PI,false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.closePath();
}
}
canvas.onmouseup = function(){
canvas.onmousemove = null;
}
</script>
</body>
</html>