canvas實現的刮刮樂程式碼例項
分享一段程式碼例項,它利用canvas實現了刮刮樂效果。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style> .demo { width: 320px; margin: 100px auto; } </style> </head> <body> <div class="main"> <div class="demo"> <canvas></canvas> </div> </div> <script> var image = new Image(); var canvas = document.querySelector("canvas"); var images = ["demo/js/img/huigu.jpg", "demo/js/img/zhuomian.jpg"]; var num = Math.floor(Math.random() * images.length); image.src = images[num]; image.addEventListener("load", function(e) { //在移動端上必須用DOM2級事件,才能用滑鼠等事件 var ctx; var w = image.width; var h = image.height; var offsetX = canvas.offsetLeft; //獲取畫布在瀏覽器視口的偏移量 var offsetY = canvas.offsetTop; var flag = false; function eventDown() { e.preventDefault(); //阻止滑鼠預設事件 flag = true; } function eventUp() { e.preventDefault(); flag = false; } function layout(ctx) { ctx.fillStyle = "gray"; //在畫布上加上一個圖層,用來遮蓋 ctx.fillRect(0, 0, w, h); } function eventMove(e) { e.preventDefault(); if (flag) { if (e.changedTouches) { //獲取手勢操作物件 e = e.changedTouches[e.changedTouches.length - 1]; } var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX; var y = (e.clientY + document.body.scrollTop || e.pageY) - offsetY; with(ctx) { //判斷當前物件 beginPath(); arc(x, y, 30, 0, Math.PI * 2); fill(); } } } canvas.width = w; canvas.height = h; canvas.style.backgroundImage = "url(" + image.src + ")"; ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, w, h); layout(ctx); ctx.globalCompositeOperation = "destination-out"; //遮蓋行為 //pc端 canvas.addEventListener("mousedown", eventDown); canvas.addEventListener("mouseup", eventUp); canvas.addEventListener("mousemove", eventMove); //移動端 canvas.addEventListener("touchstart", eventDown); canvas.addEventListener("touchend", eventUp); canvas.addEventListener("touchmove", eventMove); }) </script> </body> </html>
相關文章
- canvas刮刮樂程式碼例項Canvas
- js實現刮刮樂抽獎效果程式碼例項JS
- js刮刮樂程式碼例項JS
- canvas實現的美猴王程式碼例項Canvas
- canvas實現的驗證碼效果程式碼例項Canvas
- canvas實現的變幻線程式碼例項Canvas線程
- canvas實現的多邊形程式碼例項Canvas
- canvas實現的千輪眼程式碼例項Canvas
- canvas實現的鋸齒效果程式碼例項Canvas
- canvas實現的鐘表效果程式碼例項Canvas
- 利用canvas實現的驗證碼效果程式碼例項Canvas
- canvas實現的貪吃蛇遊戲程式碼例項Canvas遊戲
- canvas實現的雪花飄落效果程式碼例項Canvas
- canvas實現的藍色雨滴效果程式碼例項Canvas
- canvas實現的圖片縮放程式碼例項Canvas
- canvas實現的彈力小球效果程式碼例項Canvas
- canvas實現煙花燃放效果程式碼例項Canvas
- canvas實現的隨機生成漂浮小球程式碼例項Canvas隨機
- canvas實現的簡單餅狀圖程式碼例項Canvas
- canvas實現的七巧板效果程式碼例項Canvas
- canvas實現的動態心形效果程式碼例項Canvas
- canvas實現的簡單塗鴉板程式碼例項Canvas
- canvas實現的五子棋程式碼例項Canvas
- canvas實現的七色板程式碼例項Canvas
- canvas實現的圓形鐘錶效果程式碼例項Canvas
- canvas實現的簡單畫板效果程式碼例項Canvas
- angularJS結合canvas實現的畫圖程式碼例項AngularJSCanvas
- canvas實現的賽貝爾曲線效果程式碼例項Canvas
- canvas實現的小球四壁碰撞效果程式碼例項Canvas
- canvas實現的旋轉的太極圖效果程式碼例項Canvas
- canvas實現文字線性漸變效果程式碼例項Canvas
- canvas實現的卡通人物形象程式碼例項Canvas
- canvas畫圖程式碼例項Canvas
- canvas小遊戲程式碼例項Canvas遊戲
- canvas火焰效果程式碼例項Canvas
- canvas繪製實心圓形程式碼例項Canvas
- canvas實現點選產生放射性效果程式碼例項Canvas
- canvas繪製扇形程式碼例項Canvas