前言 本視頻通過59秒快速帶大家瞭解JS實現游戲刮刮樂的全過程,大家不妨可以動手嘗試一下。如萬一齣現困難可以積極與我溝通,我將無償提供技術支持及源代碼。 效果預覽 開始分析 1. 創建canvas 2. 設置圖片 3. 設置遮罩 4. 插入文檔 5. 綁定滑鼠移動事件 6. 檢查是否超出50%——移 ...
前言
本視頻通過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);