}
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';
}
// 覆蓋图片加载完成后
function coverImageLoaded(e) {
coverImgLoad = true;
fillCanvas();
canvas.style.background = 'url(' + img.src + ') no-repeat';
canvas.style.backgroundSize = that.option.backgroundSize || 'contain';
}
// 绘制canvas
function fillCanvas() {
if (that.option.coverImage.url && (!imgLoaded || !coverImgLoad)) return;
if (!that.option.coverImage.url) {
ctx.fillStyle = that.option.coverImage.color || 'gray';
ctx.fillRect(0, 0, w, h);
} else {
ctx.drawImage(coverImg, 0, 0, that.option.coverImage.width, that.option.coverImage.height);
}
ctx.globalCompositeOperation = 'destination-out';
canvas.addEventListener(tapstart, eventDown);
canvas.addEventListener(tapend, eventUp);
canvas.addEventListener(tapmove, eventMove);
}
// 点击开始事件
function eventDown(e) {
e.preventDefault();
that.mousedown = true;
}
// 点击结束事件
function eventUp(e) {
e.preventDefault();
that.mousedown = false;
}
// 刮奖事件
function eventMove(e) {
if (hasDone) return; // 刮奖结束则return
let ctx = that.ctx;
e.preventDefault();
if (that.mousedown) {
if (e.changedTouches) {
e = e.changedTouches[0];
}
var x = (e.clientX + document.body.scrollLeft || e.pageX) - that.canvasOffsetX || 0,
y = (e.clientY + document.body.scrollTop || e.pageY) - that.canvasOffsetY || 0;
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI * 2);
ctx.fill();
}
}
}
(3)刮奖完毕的实现
上述代码实现刮奖的效果,但是一般的场景是用户刮奖的面积超过一半时,覆盖图层全部散开,此时为刮奖完成的状态。
如何知道刮奖的面积超过一半了呢? canvas 中的 ctx 对象提供了一个方法 getImageData() , 该方法可返回某个区域内每个像素点的数值的组成的数组,数组中4个元素表示一个像素点的rgba值。
因此我们可以判断 rgba 中的 a 值透明度,透明度小于 256 的一半( 128 )即可视为透明状态,计算透明 a 值的百分比.









