您现在的位置是:网站首页> 编程资料编程资料

Html5 Canvas 实现一个“刮刮乐”游戏

2023-10-16 391人已围观

简介 这篇文章主要介绍了Html5 Canvas 实现一个“刮刮乐”游戏,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

之前公司项目有一个刮奖小游戏的需求,因此有了本文记录该“刮刮乐”游戏的实现过程。

话不多说,先上Demo 和 项目源码 .

 

2. 实现

我们创建一个 ScrapAward 类,通过传入 option 和调用其 restart() 方法实现重新开始。

(1)定义 option 参数及 ScrapAward 结构

 

 class ScrapAward { constructor(userOption) { this.option = { canvasId: 'canvas', // canvas的id backgroundImageUrl: '', // 背景图url width: 320, // canvas宽度 height: 160, // canvas高度 backgroundSize: '100% 100%', coverImage: { // 覆盖图层背景图url url: '', width: 320, height: 160, }, callback: () => {}, // 刮奖完成的回调函数 }; this.ctx = null; this.init(userOption); // 初始化 } // 初始化方法 init(userOption) { } // 重新开始也是一次初始化 restart(userOption) { if (userOption) { this.init(userOption); } else { this.init({}); } } }

 

(2) init 初始化

首先合并用户的配置 userOption 和默认 option , 等背景图片加载完成后调用 fillCanvas() 方法绘制覆盖层的图片后设置 canvas 的背景图。

当上述行为完成后,我们便监听鼠标或者touch事件。刮奖这一行为其实是canvas对鼠标或者touch的移动路径进行绘画,只不过是将绘画的路径变成了透明,这种效果我们通过设置 ctx.globalCompositeOperation = 'destination-out'; 即可实现。

 

 init(userOption) { // 合并用户配置 if (Object.assign) { Object.assign(this.option, userOption); } else { extend(this.option, userOption, true); } // 定义一系列变量 let that = this, img = (this.img = new Image()), //背景图片 imgLoaded = false, //背景图是否加载完成 canvas = (this.canvas = document.querySelector(`#${this.option.canvasId}`)), hastouch = 'ontouchstart' in window ? true : false, tapstart = hastouch ? 'touchstart' : 'mousedown', tapmove = hastouch ? 'touchmove' : 'mousemove', tapend = hastouch ? 'touchend' : 'mouseup', coverImg = (this.coverImg = new Image()), hasDone = false, // 是否刮奖完毕 coverImgLoad = false; that.mousedown = false; //鼠标的mousedown事件或者touchmove事件是否开启 // 移除事件监听,用于重新开始 if (this.canvas) { this.canvas.removeEventListener(tapstart, eventDown); this.canvas.removeEventListener(tapend, eventUp); this.canvas.removeEventListener(tapmove, eventMove); } coverImg.src = this.option.coverImage.url; coverImg.crossOrigin = 'Anonymous'; // 解决一些跨域问题 img.src = this.option.backgroundImageUrl; var w = (img.width = this.option.width), h = (img.height = this.option.height); this.canvasOffsetX = canvas.offsetLeft; this.canvasOffsetY = canvas.offsetTop; canvas.width = w; canvas.height = h; this.ctx = canvas.getContext('2d'); let ctx = this.ctx; this.img.addEventListener('load', backgroundImageLoaded); this.option.coverImage.url && this.coverImg.addEventListener('load', coverImageLoaded); // 背景图片加载完成后 function backgroundImageLoaded(e) { imgLoaded = true; fillCanvas(); canvas.style.background = 'url(' + img.src + ') no-repeat'; canvas.style.backgroundSize = that.option.backgroundSize || 'contain'; } // 覆

-六神源码网