前言
本视频通过59秒快速带大家了解JS实现游戏刮刮乐的全过程,大家不妨可以动手尝试一下。如万一出现困难可以积极与我沟通,我将无偿提供技术支持及源代码。
效果预览
开始分析
- 创建canvas
- 设置图片
- 设置遮罩
- 插入文档
- 绑定鼠标移动事件
- 检查是否超出50%——移除遮罩
难点、API说明
- 绘制灰色矩形
var context = canvas.getContext('2d');
context.fillStyle = 'grey';
context.fillRect(0, 0, canvas.width, canvas.height)
- 擦除canvas
let ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = "destination-out";
- 绘制圆形
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fill();
案例代码
function createCanvas() {
var canvasNode = document.createElement('canvas');
canvasNode.width = 500;
canvasNode.height = 500;
return canvasNode;
}
function append(canvas) {
var script = document.querySelector('script');
document.body.insertBefore(canvas, script);
}
function setPrize(canvas) {
let randomNum = Math.ceil(Math.random() * 7);
canvas.style.backgroundImage = 'url(./imgs/' + randomNum + '.png)';
canvas.style.backgroundSize = "100% 100%";
}
function mask(canvas) {
var context = canvas.getContext('2d');
context.fillStyle = 'grey';
context.fillRect(0, 0, canvas.width, canvas.height)
}
function checkClean(canvas) {
var ctx = canvas.getContext('2d');
var cData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
var count = 0;
for (var i = 0; i < cData.length; i += 4) {
if (cData[i] === 0) count++;
}
if (count > ((cData.length / 4) * 0.5)) {
canvas.onmousemove = null;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
function clean(canvas) {
canvas.onmousedown = function() {
canvas.onmousemove = function(e) {
let x = e.pageX - canvas.offsetLeft;
let y = e.pageY - canvas.offsetTop;
let ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fill();
checkClean(canvas);
}
}
canvas.onmouseup = function() {
canvas.onmousemove = null;
}
}
// 0:创建canvas
// 1:放置图片
// 2:设置遮罩
// 3:加入到页面
// 4:清除遮罩
var canvas = createCanvas();
setPrize(canvas);
append(canvas);
mask(canvas);
clean(canvas);