canvas實現(xiàn)刮刮卡效果
目前在html5和css3的熱潮下,html頁面的效果也是層出不窮,下面我們來介紹使用canvas來模仿刮獎刮開效果。
原理
在需要刮出的圖片或者文字上方蓋上一層灰色或者其他背景的canvas畫布,當(dāng)手指或者鼠標(biāo)點擊畫布并移動時,將畫布上移動過的軌跡變成透明即可。
分析
demo中在class為content的div上蓋上一層灰色的畫布,然后通過獲取鼠標(biāo)和手指的坐標(biāo)計算出在畫布位置上的坐標(biāo),通過在坐標(biāo)原點位置畫一個半徑10px的透明圓形來透過畫布,顯示出畫布下的內(nèi)容。本demo是用時需要改變的內(nèi)容為_width,_height,touchTop,touchLeft這幾個參數(shù),根據(jù)自身畫布的位置自行計算即可。由于是長按事件,記得在移動端阻止瀏覽器默認(rèn)功能。
效果圖:

圖(1)初始圖

圖(2)刮開效果
代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標(biāo)題文檔</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
<style>
.content,.cover{width:400px; height:400px; position:absolute; left:50%; top:50%; margin:-200px 0 0 -200px;}
.content{ font-size:48px; line-height:400px; text-align:center;}
h3{ text-align:center; line-height:200px;}
</style>
</head>
<body>
<h3>快來刮開?。?!</h3>
<div class="content" >中獎啦~!</div>
<canvas id="cover" class="cover" width="400" height="400"></canvas>
</body>
<script>
var isdown = false,
cover = document.getElementById("cover"),
covercanvas = cover.getContext("2d");
//
covercanvas.fillStyle="transparent";
covercanvas.fillRect(0,0,400,400);
function fillter( canvas ){
canvas.fillStyle="#ccc";
canvas.fillRect(0,0,400,400);
}
function isDown(e){
e.preventDefault();
isdown=true;
}
function isUp(e){
isdown=false;
}
function draw( e ){
e.preventDefault();
if(isdown){
if(e.changedTouches){
e=e.changedTouches[e.changedTouches.length-1];
}
var _height= parseInt((window.innerHeight-400)/2),
_width= parseInt((window.innerWidth-400)/2),
touchTop=e.clientY - _height,
touchLeft=e.clientX - _width;
with(covercanvas){
beginPath();
arc(touchLeft, touchTop, 10, 0, Math.PI * 2);
fill();
}
}
//alert(touchTop);
}
fillter(covercanvas);
covercanvas.globalCompositeOperation = 'destination-out';
cover.addEventListener('touchstart',isDown);
cover.addEventListener('touchmove',draw);
cover.addEventListener('touchend',isUp);
cover.addEventListener('mousemove',draw);
cover.addEventListener('mousedown',isDown);
cover.addEventListener('mouseup',isUp);
</script>
</html>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
細(xì)數(shù)promise與async/await的使用及區(qū)別說明
這篇文章主要介紹了細(xì)數(shù)promise與async/await的使用及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

