代码改变世界

canvas 写一个刮刮乐抽奖

2018-10-11 13:59  muamaker  阅读(441)  评论(0编辑  收藏  举报

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<style type="text/css">
			*{
				padding: 0;
				margin: 0;
			}

			.wap{
				width: 200px;
				height: 40px;
				position: relative;
				margin: 20px auto;
				border: 1px solid #3385FF;
			}
			#canvas,.text{
				position: absolute;
				top: 0;
				left: 0;
				width: 200px;
				height: 40px;
			}
			.text{
				line-height: 40px;
				text-align: center;
				font-size: 30px;
				color: gold;
				z-index: 1;
				display: none;
			}
			#canvas{
				z-index: 10;
			}
		</style>
	</head>
	<body>
		
		<div class="wap">
			<div class="text">一等奖</div>
			<canvas id="canvas" width="200" height="40" ></canvas>
		</div>
		
	</body>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		var canvas = document.getElementById('canvas');
		
		var ctx = canvas.getContext('2d');
		
		var pos = $('.wap').offset();
		
		
		
		ctx.fillStyle = '#ccc';
		
		ctx.fillRect(0,0,canvas.width,canvas.height);

		$('.text').css({display:"block"});
		ctx.globalCompositeOperation = 'destination-out';
		
		ctx.beginPath();
		ctx.fillStyle = 'red';
		ctx.strokeStyle = 'red'
		ctx.lineWidth = 5;
		
		canvas.onmousedown = function(e){
			this.run = true;
			ctx.moveTo(e.clientX-pos.left,e.clientY-pos.top);
		}
		
		canvas.onmousemove = function(e){
			if(this.run){
				console.log(e.clientX-pos.left,e.clientY-pos.top)
				ctx.lineTo(e.clientX-pos.left,e.clientY-pos.top);
				ctx.stroke();
			}
		}
		
		canvas.onmouseup = function(e){
			ctx.stroke();
			this.run = false;
		}
		
		/*
		 *copy:只绘制新图形,删除其它的所有内容
		 * darker:在图形重叠的地方,其颜色由两个颜色值相减后决定
		 * destination-atop:画布上已有的内容只会在它和新图形重叠的地方保留,新图形绘制于内容之后
		 * destination-in:在新图形及画布上已有图形重叠的地方,画布上已有的重叠内容都保留。所有其他的内容都透明
		 * destination-out:画布原始内容没有重叠的保留,重叠的和新画的,都是透明(刮刮乐);
		 * destination-over:新图形绘制于画布上已有内容的后面
		 * ligther:在图形重叠的地方,其颜色由两个颜色值相加后决定
		 * source-atop:只有在新图形和画布上已有内容重叠的地方才绘制新的图形
		 * source-in:在新图形和画布上已有内容重叠的地方才绘制新图形。其他内容均透明
		 * source-out:只有在新图形和画布上已有内容不重叠的地方才绘制新的图形
		 * source-over:新图形绘制于画布已有图形的顶部。默认设置
		 * xor:重叠的地方透明,其他的地方正常画
		 * 
		 * 
		 * */
		
	</script>
</html>