search
HomeWeb Front-endH5 TutorialHTML5/CSS3 special topic canvas simulation to implement electronic lottery scratch-off sample code (picture)

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:


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


##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>

2. First of all, I used a canvas auxiliary class that I wrote before, which I will use today. Some methods:

/**
 * 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;
    }


}

This class also simply encapsulates the Canvas object, sets parameters, draws graphics, etc. It 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;
    }
};

passes the two canvas ids passed in by the user, and then generates an object, performs initialization operations, and sets events. Of course, it also provides users with optional parameters, various colors, information displayed after scraping, etc. Through {
FrontFillcolor: "Silver",
Backfillcolor: "Gold",
Backfontcolor: " Red ",
Backfontsize: 24,
MSG:" Thank you Hui Gu "
}; passed to the init method for settings.

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:


Cause: breakpoint generated due to the mouse moving too fast; solution : Split the left side of the mouse twice in mousemove into multiple breakpoint coordinates:



As shown above, Connect a line between two points, divide it into multiple small segments according to the slope, and obtain the coordinates on the line segments 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;

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;
    }
}

The above is the detailed content of HTML5/CSS3 special topic canvas simulation to implement electronic lottery scratch-off sample code (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function