html5中canvas畫布實現手機端和移動端的刮刮樂效果
阿新 • • 發佈:2019-01-25
用html5中的canvas實現刮刮樂的效果
- 使用html+css實現背景的樣式
- 使用clearRect()方法實現掛去的作用
- 手機端使用addEventListener()監聽
- 手機端滑動事件touchmove
實現的效果圖
此圖背景是來自網路
html部分程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>刮刮樂</title>
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="js/api.js" type="text/javascript"></script>
<style>
.content{
width:900px;
height: 500px;
background: url("images/zj.jpg") no-repeat;
margin: 0 auto;
overflow: hidden;
position : relative
}
p{ width: 300px;height: 50px; background: #fff; margin: 0 auto; margin-top: 380px; margin-left: 360px; line-height: 50px;
text-align: center;display: block; }
#Canvas{ margin-left: 360px;position: absolute; bottom: 70px;cursor: pointer}
</style>
</head>
<body>
<div class="content">
<p>謝謝惠顧</p>
<canvas width="300" height="50" id="Canvas">你的瀏覽器版本太低</canvas>
</div>
</body>
</html>
js程式碼:
window.onload=function(e){
var canva=document.getElementById("Canvas");
if(canva.getContext){
var inghei=100;
canva2D=canva.getContext("2d");
canva2D.fillStyle="#ccc";
canva2D.fillRect(0,0,300,50);
//滑鼠移動到“灰色上”
canva.onmousemove=function(e){
var canavOffest = $(canva).offset();
var canvX=Math.floor(e.pageX - canavOffest.left);
var canvY=Math.floor(e.pageY-canavOffest.top);
var canvY =canvY+ parseInt(inghei);
lottery(canvX,canvY,canva2D);
}
function lottery(x,y,c){
c.clearRect(x,y-inghei,20,20);
}
//移動端手滑動
canva.addEventListener('touchmove',function(event){
//如果觸屏時只有一隻手
if(event.targetTouches.length == 1){
event.preventDefault();// 阻止瀏覽器預設事件,重要
var touch = event.targetTouches[0];
var canavOffest = $(canva).offset();
var canvX=Math.floor(touch.pageX - canavOffest.left);
var canvY=Math.floor(touch.pageY-canavOffest.top);
var canvY =canvY+ parseInt(inghei);
lottery(touch.canvX,touch.canvY,canva2D);
}
},false);
}
}