继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

大众学开发——59秒学习编写刮刮乐游戏

凃老师
关注TA
已关注
手记 20
粉丝 6
获赞 57

前言

本视频通过59秒快速带大家了解JS实现游戏刮刮乐的全过程,大家不妨可以动手尝试一下。如万一出现困难可以积极与我沟通,我将无偿提供技术支持及源代码。

效果预览

图片描述

开始分析

  1. 创建canvas
  2. 设置图片
  3. 设置遮罩
  4. 插入文档
  5. 绑定鼠标移动事件
  6. 检查是否超出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";
  • 绘制圆形file
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);

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP