Home Web Front-end CSS Tutorial Canvas simulates the implementation of electronic lottery scratch tickets

Canvas simulates the implementation of electronic lottery scratch tickets

Feb 28, 2017 pm 01:57 PM

Today I will bring you a small example of a scratch-off game~based on HTML5 canvas. If you are interested, you can change it to the Android version, or other~

Rendering:

canvas 模拟实现电子彩票刮刮乐

Post a photo of me winning 5 million, what should I do, how to spend it~

canvas 模拟实现电子彩票刮刮乐

Okay, let’s start with the principle:

1. There are two Canvas in the scratch area, one is front and one is back. The front covers the canvas below.

2. The canvas is filled with a rectangle by default, covering the canvas rendering below, then listening to the mouse event, and erasing the rectangular area on the front canvas according to the x, y coordinates of mousemove, and then displaying the following Canvas renderings.

It’s very simple~hehe~

1. HTML file content:

<!DOCTYPE html>  
<html>  
<head>  
    <title></title>  
    <meta charset="utf-8">  
  
    <script type="text/javascript" src="../../jquery-1.8.3.js"></script>  
    <script type="text/javascript" src="canvas2d.js"></script>  
  
    <script type="text/javascript" src="GuaGuaLe2.js"></script>  
  
    <script type="text/javascript">  
  
        $(function ()  
        {  
            var guaguale = new GuaGuaLe("front", "back");  
            guaguale.init({msg: "¥5000000.00"});  
        });  
    </script>  
    <style type="text/css">  
  
  
        body  
        {  
            background: url("s_bd.jpg") repeat 0 0;  
        }  
  
        .container  
        {  
            position: relative;  
            width: 400px;  
            height: 160px;  
            margin: 100px auto 0;  
            background: url(s_title.png) no-repeat 0 0;  
            background-size: 100% 100%;  
        }  
  
        #front, #back  
        {  
            position: absolute;  
            width: 200px;  
            left: 50%;  
            top: 100%;  
            margin-left: -130px;  
            height: 80px;  
            border-radius: 5px;  
            border: 1px solid #444;  
        }  
  
    </style>  
  
</head>  
<body>  
  
<p class="container">  
    <canvas id="back" width="200" height="80"></canvas>  
    <canvas id="front" width="200" height="80"></canvas>  
</p>  
  
  
</body>  
</html>
Copy after login

2. First, I used a The canvas auxiliary class written before leaves behind some methods that I will use today:

/** 
 * Created with JetBrains WebStorm. 
 * User: zhy 
 * Date: 13-12-17 
 * Time: 下午9:42 
 * To change this template use File | Settings | File Templates. 
 */  
  
function Canvas2D($canvas)  
{  
    var context = $canvas[0].getContext("2d"),  
        width = $canvas[0].width,  
        height = $canvas[0].height,  
        pageOffset = $canvas.offset();  
  
  
    context.font = "24px Verdana, Geneva, sans-serif";  
    context.textBaseline = "top";  
  
  
    /** 
     * 绘制矩形 
     * @param start 
     * @param end 
     * @param isFill 
     */  
    this.drawRect = function (start, end, isFill)  
    {  
        var w = end.x - start.x , h = end.y - start.y;  
        if (isFill)  
        {  
            context.fillRect(start.x, start.y, w, h);  
        }  
        else  
        {  
            context.strokeRect(start.x, start.y, w, h);  
        }  
    };  
  
    /** 
     * 根据书写的文本,得到该文本在canvas上书写的中心位置的左上角坐标 
     * @param text 
     * @returns {{x: number, y: number}} 
     */  
    this.caculateTextCenterPos = function (text)  
    {  
        var metrics = context.measureText(text);  
        console.log(metrics);  
//        context.font = fontSize + "px Verdana, Geneva, sans-serif";  
        var textWidth = metrics.width;  
        var textHeight = parseInt(context.font);  
  
        return {  
            x: width / 2 - textWidth / 2,  
            y: height / 2 - textHeight / 2  
        };  
    }  
    this.width = function ()  
    {  
        return width;  
    }  
    this.height = function ()  
    {  
        return height;  
    }  
    this.resetOffset = function ()  
    {  
        pageOffset = $canvas.offset();  
    }  
    /** 
     * 当屏幕大小发生变化,重新计算offset 
     */  
    $(window).resize(function ()  
    {  
        pageOffset = $canvas.offset();  
    });  
  
    /** 
     * 将页面上的左边转化为canvas中的坐标 
     * @param pageX 
     * @param pageY 
     * @returns {{x: number, y: number}} 
     */  
    this.getCanvasPoint = function (pageX, pageY)  
    {  
        return{  
            x: pageX - pageOffset.left,  
            y: pageY - pageOffset.top  
        }  
    }  
    /** 
     * 清除区域,此用户鼠标擦出刮奖涂层 
     * @param start 
     * @returns {*} 
     */  
    this.clearRect = function (start)  
    {  
        context.clearRect(start.x, start.y, 10, 10);  
        return this;  
    };  
  
    /** 
     *将文本绘制到canvas的中间 
     * @param text 
     * @param fill 
     */  
    this.drawTextInCenter = function (text, fill)  
    {  
        var point = this.caculateTextCenterPos(text);  
        if (fill)  
        {  
            context.fillText(text, point.x, point.y);  
        }  
        else  
        {  
            context.strokeText(text, point.x, point.y);  
        }  
    };  
    /** 
     * 设置画笔宽度 
     * @param newWidth 
     * @returns {*} 
     */  
    this.penWidth = function (newWidth)  
    {  
        if (arguments.length)  
        {  
            context.lineWidth = newWidth;  
            return this;  
        }  
        return context.lineWidth;  
    };  
  
    /** 
     * 设置画笔颜色 
     * @param newColor 
     * @returns {*} 
     */  
    this.penColor = function (newColor)  
    {  
        if (arguments.length)  
        {  
            context.strokeStyle = newColor;  
            context.fillStyle = newColor;  
            return this;  
        }  
  
        return context.strokeStyle;  
    };  
  
    /** 
     * 设置字体大小 
     * @param fontSize 
     * @returns {*} 
     */  
    this.fontSize = function (fontSize)  
    {  
        if (arguments.length)  
        {  
            context.font = fontSize + "px Verdana, Geneva, sans-serif";  
  
            return this;  
        }  
  
        return context.fontSize;  
    }  
  
  
}
Copy after login

This class also simply encapsulates the Canvas object and sets parameters. , drawing graphics or something, is relatively simple, you can improve this class~

3, GuaGuaLe.js

/** 
 * Created with JetBrains WebStorm. 
 * User: zhy 
 * Date: 14-6-24 
 * Time: 上午11:36 
 * To change this template use File | Settings | File Templates. 
 */  
function GuaGuaLe(idFront, idBack)  
{  
    this.$eleBack = $("#" + idBack);  
    this.$eleFront = $("#" + idFront);  
    this.frontCanvas = new Canvas2D(this.$eleFront);  
    this.backCanvas = new Canvas2D(this.$eleBack);  
  
    this.isStart = false;  
  
}  
  
GuaGuaLe.prototype = {  
    constructor: GuaGuaLe,  
    /** 
     * 将用户的传入的参数和默认参数做合并 
     * @param desAttr 
     * @returns {{frontFillColor: string, backFillColor: string, backFontColor: string, backFontSize: number, msg: string}} 
     */  
    mergeAttr: function (desAttr)  
    {  
        var defaultAttr = {  
            frontFillColor: "silver",  
            backFillColor: "gold",  
            backFontColor: "red",  
            backFontSize: 24,  
            msg: "谢谢惠顾"  
        };  
        for (var p in  desAttr)  
        {  
            defaultAttr[p] = desAttr[p];  
        }  
  
        return defaultAttr;  
  
    },  
  
  
    init: function (desAttr)  
    {  
  
        var attr = this.mergeAttr(desAttr);  
  
        //初始化canvas  
        this.backCanvas.penColor(attr.backFillColor);  
        this.backCanvas.fontSize(attr.backFontSize);  
        this.backCanvas.drawRect({x: 0, y: 0}, {x: this.backCanvas.width(), y: this.backCanvas.height()}, true);  
        this.backCanvas.penColor(attr.backFontColor);  
        this.backCanvas.drawTextInCenter(attr.msg, true);  
        //初始化canvas  
        this.frontCanvas.penColor(attr.frontFillColor);  
        this.frontCanvas.drawRect({x: 0, y: 0}, {x: this.frontCanvas.width(), y: this.frontCanvas.height()}, true);  
  
        var _this = this;  
        //设置事件  
        this.$eleFront.mousedown(function (event)  
        {  
            _this.mouseDown(event);  
        }).mousemove(function (event)  
            {  
                _this.mouseMove(event);  
            }).mouseup(function (event)  
            {  
                _this.mouseUp(event);  
            });  
    },  
    mouseDown: function (event)  
    {  
        this.isStart = true;  
        this.startPoint = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY);  
    },  
    mouseMove: function (event)  
    {  
        if (!this.isStart)return;  
        var p = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY);  
        this.frontCanvas.clearRect(p);  
    },  
    mouseUp: function (event)  
    {  
        this.isStart = false;  
    }  
};
Copy after login
Copy after login

Passed in through the user The IDs of the two canvases, then generate an object, perform initialization operations, and set events. Of course, it also provides users with the option to set optional parameters, various colors, information displayed after scraping, etc., which can be set by passing

{
            frontFillColor: "silver",
            backFillColor: "gold",
            backFontColor: "red",
            backFontSize: 24,
            msg: "谢谢惠顾"
        };
Copy after login

to the init method. .

Okay, then it’s basically finished. Let’s test it:

The layer scraping is basically realized, but there is a small problem, that is, when the user slides very fast, there will be some interruptions. Of course, you can ignore it, but we are going to provide a solution:

canvas 模拟实现电子彩票刮刮乐

Cause: The breakpoint is generated due to the mouse moving too fast; Solution: Move mousemove Click the left side of the mouse twice and split it into multiple breakpoint coordinates:

canvas 模拟实现电子彩票刮刮乐

As shown above, connect the two points with a line and divide it into multiple breakpoints according to the slope. Each small segment, obtain the coordinates on the line segment respectively (there are four possibilities, you can draw a picture if you are interested, and calculate it, the code is as follows):

var k;  
      if (p.x > this.startPoint.x)  
      {  
          k = (p.y - this.startPoint.y) / (p.x - this.startPoint.x);  
          for (var i = this.startPoint.x; i < p.x; i += 5)  
          {  
              this.frontCanvas.clearRect({x: i, y: (this.startPoint.y + (i - this.startPoint.x) * k)});  
          }  
      } else  
      {  
          k = (p.y - this.startPoint.y) / (p.x - this.startPoint.x);  
          for (var i = this.startPoint.x; i > p.x; i -= 5)  
          {  
              this.frontCanvas.clearRect({x: i, y: (this.startPoint.y + ( i - this.startPoint.x  ) * k)});  
          }  
      }  
      this.startPoint = p;
Copy after login

4. Finally Post the complete GuaGuaLe.js

/** 
 * Created with JetBrains WebStorm. 
 * User: zhy 
 * Date: 14-6-24 
 * Time: 上午11:36 
 * To change this template use File | Settings | File Templates. 
 */  
function GuaGuaLe(idFront, idBack)  
{  
    this.$eleBack = $("#" + idBack);  
    this.$eleFront = $("#" + idFront);  
    this.frontCanvas = new Canvas2D(this.$eleFront);  
    this.backCanvas = new Canvas2D(this.$eleBack);  
  
    this.isStart = false;  
  
}  
  
GuaGuaLe.prototype = {  
    constructor: GuaGuaLe,  
    /** 
     * 将用户的传入的参数和默认参数做合并 
     * @param desAttr 
     * @returns {{frontFillColor: string, backFillColor: string, backFontColor: string, backFontSize: number, msg: string}} 
     */  
    mergeAttr: function (desAttr)  
    {  
        var defaultAttr = {  
            frontFillColor: "silver",  
            backFillColor: "gold",  
            backFontColor: "red",  
            backFontSize: 24,  
            msg: "谢谢惠顾"  
        };  
        for (var p in  desAttr)  
        {  
            defaultAttr[p] = desAttr[p];  
        }  
  
        return defaultAttr;  
  
    },  
  
  
    init: function (desAttr)  
    {  
  
        var attr = this.mergeAttr(desAttr);  
  
        //初始化canvas  
        this.backCanvas.penColor(attr.backFillColor);  
        this.backCanvas.fontSize(attr.backFontSize);  
        this.backCanvas.drawRect({x: 0, y: 0}, {x: this.backCanvas.width(), y: this.backCanvas.height()}, true);  
        this.backCanvas.penColor(attr.backFontColor);  
        this.backCanvas.drawTextInCenter(attr.msg, true);  
        //初始化canvas  
        this.frontCanvas.penColor(attr.frontFillColor);  
        this.frontCanvas.drawRect({x: 0, y: 0}, {x: this.frontCanvas.width(), y: this.frontCanvas.height()}, true);  
  
        var _this = this;  
        //设置事件  
        this.$eleFront.mousedown(function (event)  
        {  
            _this.mouseDown(event);  
        }).mousemove(function (event)  
            {  
                _this.mouseMove(event);  
            }).mouseup(function (event)  
            {  
                _this.mouseUp(event);  
            });  
    },  
    mouseDown: function (event)  
    {  
        this.isStart = true;  
        this.startPoint = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY);  
    },  
    mouseMove: function (event)  
    {  
        if (!this.isStart)return;  
        var p = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY);  
        this.frontCanvas.clearRect(p);  
    },  
    mouseUp: function (event)  
    {  
        this.isStart = false;  
    }  
};
Copy after login
Copy after login

. The above is the entire content of this article. I hope it will be helpful to everyone’s learning. I also hope everyone will support the PHP Chinese website. .

For more canvas simulation and implementation of electronic lottery scratch-off related articles, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Demystifying Screen Readers: Accessible Forms & Best Practices Demystifying Screen Readers: Accessible Forms & Best Practices Mar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Create a JavaScript Contact Form With the Smart Forms Framework Create a JavaScript Contact Form With the Smart Forms Framework Mar 07, 2025 am 11:33 AM

This tutorial demonstrates creating professional-looking JavaScript forms using the Smart Forms framework (note: no longer available). While the framework itself is unavailable, the principles and techniques remain relevant for other form builders.

Adding Box Shadows to WordPress Blocks and Elements Adding Box Shadows to WordPress Blocks and Elements Mar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let&#039;s look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte Transition Making Your First Custom Svelte Transition Mar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Show, Don't Tell Show, Don't Tell Mar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

Classy and Cool Custom CSS Scrollbars: A Showcase Classy and Cool Custom CSS Scrollbars: A Showcase Mar 10, 2025 am 11:37 AM

In this article we will be diving into the world of scrollbars. I know, it doesn’t sound too glamorous, but trust me, a well-designed page goes hand-in-hand

What the Heck Are npm Commands? What the Heck Are npm Commands? Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

See all articles