首页 > 代码库 > 实现刮刮乐的效果

实现刮刮乐的效果

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
		</style>
	</head>

	<body>
		<div id="box">
			<img src="http://www.mamicode.com/img/1.jpg" style="width: 700px;height: 500px;" />
			<canvas id="myCanvas" width="700" height="500" style="position: absolute; left: 0px;top: 0px;"></canvas>
		</div>
	</body>
	<script type="text/javascript">
		var myCanvas = document.getElementById(‘myCanvas‘);
		var context = myCanvas.getContext(‘2d‘);
		//设置一个灰色矩形的画布 将图片盖住
		context.fillStyle = ‘gray‘;
		context.fillRect(0, 0, 700, 500);

		myCanvas.onmousedown = function(e) {
			//获取鼠标按下时鼠标的坐标
			var X = e.clientX - box.offsetLeft;
			var Y = e.clientY - box.offsetTop;
			//绘制起点
			context.beginPath();
			context.moveTo(X, Y);
			myCanvas.onmousemove = function(e) {
				//移动的时候开始绘制 获取此时的鼠标坐标
				var x = e.clientX - box.offsetLeft;
				var y = e.clientY - box.offsetTop;
				//让绘制区域重合部分显示透明
				context.globalCompositeOperation = "destination-out";

				context.lineTo(x, y);
				//修饰一下线条 
				context.lineCap = ‘round‘;
				context.lineWidth = 30;
				context.stroke();

				//当刮到一半的时候,显示全图
				//获取画布上的所有数据
				var imgData = http://www.mamicode.com/context.getImageData(0, 0, 700, 500);>

  开始用用矩形或球形来当笔触,如果移动的过快浏览器有一个反应时间,会让刮的区域中间形成间隙.用线条来当笔触,适当的修饰笔触,可避免这个现象.

实现刮刮乐的效果