canvas实现刮奖功能

素颜马尾好姑娘i 2024-02-20 12:37 98阅读 0赞

canvas刮奖原理很简单,就是在刮奖区添加两个canvas,第一个canvas用于显示刮开后显示的内容,可以是一张图片或一个字符串,第二个canvas用于显示涂层,可以用一张图片或用纯色填充,第二个canvas覆盖在第一个canvas上面。

当在第二个canvas上点击或涂抹(点击然后拖动鼠标)时,把点击区域变为透明,这样就可以看到第一个canvas上的内容,即实现了刮奖效果。

效果图

在这里插入图片描述

源代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>_直接复制网</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1 ,user-scalable=no">
  7. <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
  8. <style>
  9. #lotteryContainer {
  10. position:relative;
  11. width: 300px;
  12. height:100px;
  13. }
  14. #drawPercent {
  15. color:#F60;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <button id="freshBtn">刷新</button><label>已刮开 <span id="drawPercent">0%</span> 区域。</label>
  21. <div id="lotteryContainer"></div>
  22. <script>
  23. function Lottery(id, cover, coverType, width, height, drawPercentCallback) {
  24. this.conId = id;
  25. this.conNode = document.getElementById(this.conId);
  26. this.cover = cover;
  27. this.coverType = coverType;
  28. this.background = null;
  29. this.backCtx = null;
  30. this.mask = null;
  31. this.maskCtx = null;
  32. this.lottery = null;
  33. this.lotteryType = 'image';
  34. this.width = width || 300;
  35. this.height = height || 100;
  36. this.clientRect = null;
  37. this.drawPercentCallback = drawPercentCallback;
  38. }
  39. Lottery.prototype = {
  40. createElement: function (tagName, attributes) {
  41. var ele = document.createElement(tagName);
  42. for (var key in attributes) {
  43. ele.setAttribute(key, attributes[key]);
  44. }
  45. return ele;
  46. },
  47. getTransparentPercent: function(ctx, width, height) {
  48. var imgData = ctx.getImageData(0, 0, width, height),
  49. pixles = imgData.data,
  50. transPixs = [];
  51. for (var i = 0, j = pixles.length; i < j; i += 4) {
  52. var a = pixles[i + 3];
  53. if (a < 128) {
  54. transPixs.push(i);
  55. }
  56. }
  57. return (transPixs.length / (pixles.length / 4) * 100).toFixed(2);
  58. },
  59. resizeCanvas: function (canvas, width, height) {
  60. canvas.width = width;
  61. canvas.height = height;
  62. canvas.getContext('2d').clearRect(0, 0, width, height);
  63. },
  64. drawPoint: function (x, y) {
  65. this.maskCtx.beginPath();
  66. var radgrad = this.maskCtx.createRadialGradient(x, y, 0, x, y, 30);
  67. radgrad.addColorStop(0, 'rgba(0,0,0,0.6)');
  68. radgrad.addColorStop(1, 'rgba(255, 255, 255, 0)');
  69. this.maskCtx.fillStyle = radgrad;
  70. this.maskCtx.arc(x, y, 30, 0, Math.PI * 2, true);
  71. this.maskCtx.fill();
  72. if (this.drawPercentCallback) {
  73. this.drawPercentCallback.call(null, this.getTransparentPercent(this.maskCtx, this.width, this.height));
  74. }
  75. },
  76. bindEvent: function () {
  77. var _this = this;
  78. var device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
  79. var clickEvtName = device ? 'touchstart' : 'mousedown';
  80. var moveEvtName = device? 'touchmove': 'mousemove';
  81. if (!device) {
  82. var isMouseDown = false;
  83. document.addEventListener('mouseup', function(e) {
  84. isMouseDown = false;
  85. }, false);
  86. } else {
  87. document.addEventListener("touchmove", function(e) {
  88. if (isMouseDown) {
  89. e.preventDefault();
  90. }
  91. }, false);
  92. document.addEventListener('touchend', function(e) {
  93. isMouseDown = false;
  94. }, false);
  95. }
  96. this.mask.addEventListener(clickEvtName, function (e) {
  97. isMouseDown = true;
  98. var docEle = document.documentElement;
  99. if (!_this.clientRect) {
  100. _this.clientRect = {
  101. left: 0,
  102. top:0
  103. };
  104. }
  105. var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft;
  106. var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop;
  107. _this.drawPoint(x, y);
  108. }, false);
  109. this.mask.addEventListener(moveEvtName, function (e) {
  110. if (!device && !isMouseDown) {
  111. return false;
  112. }
  113. var docEle = document.documentElement;
  114. if (!_this.clientRect) {
  115. _this.clientRect = {
  116. left: 0,
  117. top:0
  118. };
  119. }
  120. var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft;
  121. var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop;
  122. _this.drawPoint(x, y);
  123. }, false);
  124. },
  125. drawLottery: function () {
  126. this.background = this.background || this.createElement('canvas', {
  127. style: 'position:absolute;left:0;top:0;'
  128. });
  129. this.mask = this.mask || this.createElement('canvas', {
  130. style: 'position:absolute;left:0;top:0;'
  131. });
  132. if (!this.conNode.innerHTML.replace(/[\w\W]| /g, '')) {
  133. this.conNode.appendChild(this.background);
  134. this.conNode.appendChild(this.mask);
  135. this.clientRect = this.conNode ? this.conNode.getBoundingClientRect() : null;
  136. this.bindEvent();
  137. }
  138. this.backCtx = this.backCtx || this.background.getContext('2d');
  139. this.maskCtx = this.maskCtx || this.mask.getContext('2d');
  140. if (this.lotteryType == 'image') {
  141. var image = new Image(),
  142. _this = this;
  143. image.onload = function () {
  144. _this.width = this.width;
  145. _this.height = this.height;
  146. _this.resizeCanvas(_this.background, this.width, this.height);
  147. _this.backCtx.drawImage(this, 0, 0);
  148. _this.drawMask();
  149. }
  150. image.src = this.lottery;
  151. } else if (this.lotteryType == 'text') {
  152. this.width = this.width;
  153. this.height = this.height;
  154. this.resizeCanvas(this.background, this.width, this.height);
  155. this.backCtx.save();
  156. this.backCtx.fillStyle = '#FFF';
  157. this.backCtx.fillRect(0, 0, this.width, this.height);
  158. this.backCtx.restore();
  159. this.backCtx.save();
  160. var fontSize = 30;
  161. this.backCtx.font = 'Bold ' + fontSize + 'px Arial';
  162. this.backCtx.textAlign = 'center';
  163. this.backCtx.fillStyle = '#F60';
  164. this.backCtx.fillText(this.lottery, this.width / 2, this.height / 2 + fontSize / 2);
  165. this.backCtx.restore();
  166. this.drawMask();
  167. }
  168. },
  169. drawMask: function() {
  170. this.resizeCanvas(this.mask, this.width, this.height);
  171. if (this.coverType == 'color') {
  172. this.maskCtx.fillStyle = this.cover;
  173. this.maskCtx.fillRect(0, 0, this.width, this.height);
  174. this.maskCtx.globalCompositeOperation = 'destination-out';
  175. } else if (this.coverType == 'image'){
  176. var image = new Image(),
  177. _this = this;
  178. image.onload = function () {
  179. _this.maskCtx.drawImage(this, 0, 0);
  180. _this.maskCtx.globalCompositeOperation = 'destination-out';
  181. }
  182. image.src = this.cover;
  183. }
  184. },
  185. init: function (lottery, lotteryType) {
  186. this.lottery = lottery;
  187. this.lotteryType = lotteryType || 'image';
  188. this.drawLottery();
  189. }
  190. }
  191. window.onload = function () {
  192. var lottery = new Lottery('lotteryContainer', '#CCC', 'color', 300, 100, drawPercent);
  193. lottery.init('http://www.baidu.com/img/bdlogo.gif', 'image');
  194. document.getElementById('freshBtn').onclick = function() {
  195. drawPercentNode.innerHTML = '0%';
  196. lottery.init(getRandomStr(10), 'text');
  197. }
  198. var drawPercentNode = document.getElementById('drawPercent');
  199. function drawPercent(percent) {
  200. drawPercentNode.innerHTML = percent + '%';
  201. }
  202. }
  203. function getRandomStr(len) {
  204. var text = "";
  205. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  206. for( var i=0; i < len; i++ )
  207. text += possible.charAt(Math.floor(Math.random() * possible.length));
  208. return text;
  209. }
  210. </script>
  211. </body>
  212. </html>

发表评论

表情:
评论列表 (有 0 条评论,98人围观)

还没有评论,来说两句吧...

相关阅读

    相关 canvas应用----

    最近在学习html5,为了更好地学习和帮助其他人我决定把我写过的案例写下来~~ 先说一下刮刮乐这个程序实现的注意点 材料:一张图片和canvas画布 在html