search
HomeWeb Front-endH5 TutorialHTML5 uses canvas to achieve verification code effect (code example)

Usually we can see the verification code on the login interface. The function of the verification code is to detect whether a human is operating, prevent non-human operations such as machines, and prevent the database from being easily broken. Generally, verification codes are written in back-end languages ​​such as PHP and Java; in fact, verification codes can also be implemented using front-end technology: use canvas or SVG to draw the verification code. This chapter introduces how to use canvas to draw verification codes (code examples) in HTML5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

canvas verification code display effect:

Click to change (redraw) verification code:

HTML5 uses canvas to achieve verification code effect (code example)

Run the function output on the console and return Value (verification code):

HTML5 uses canvas to achieve verification code effect (code example)

Code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas验证码</title>
</head>

<body>
    <canvas width="200" height="60" id="check" style="border:1px solid #000;">您的浏览器不支持canvas标签!</canvas>
    <script>
        var ctx = document.getElementById("check").getContext("2d");
        var ctxW = document.getElementById("check").clientWidth;
        var ctxH = document.getElementById("check").clientHeight;

        /**
         * 产生一个随机数  可设置随机数区间
         * @param  {[Number]} min [随机数区间下限]
         * @param  {[Number]} max [随机数区间上限]
         * @return {[Number]}     [返回一个在此区间的随机数]
         */
        function ranNum(min, max) {

            return Math.random() * (max - min) + min;

        }

        /**
         * 返回一个随机颜色 可设置颜色区间
         * @param  {[Number]} min [颜色下限]
         * @param  {[Number]} max [颜色上限]
         * @return {[String]}     [随机颜色]
         */
        function ranColor(min, max) {

            var r = ranNum(min, max);

            var g = ranNum(min, max);

            var b = ranNum(min, max);

            // return "rgb(" + r + "," + g + "," + b + ")";
            return `rgb(${r},${g},${b})`;

        }

        /**
         * 随机字符串数组
         * @return {[Array]} [随机数组]
         */
        function ranStr() {

            var str = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";

            return str.split("").sort(function () {
                return Math.random() - 0.5
            });

        }

        /**
         * 绘制文本字符串
         * @param  {[String]} canvasId [canvas的id]
         * @param  {[Number]} canvasW  [canvas的width]
         * @param  {[Number]} canvasH  [canvas的height]
         * @param  {[Number]} num      [绘制验证码的字数]
         * @param  {[Number]} fsMin    [字体大小下限]
         * @param  {[Number]} fsMax    [字体大小上限]
         * @param  {[Number]} frMin    [字体旋转偏移下限]
         * @param  {[Number]} frMax    [字体旋转偏移上限]
         * @param  {[Number]} min      [颜色下限]
         * @param  {[Number]} max      [颜色上限]
         * @return {[String]} [随机字符串]
         */
        function drawText(canvasId, canvasW, canvasH, num, fsMin, fsMax, frMin, frMax, min, max) {

            var str = "";

            for (var i = 0; i < num; i++) {

                var char = ranStr()[Math.floor(0, ranStr().length)];

                var fs = ranNum(fsMin, fsMax);

                canvasId.font = fs + "px Verdana";

                canvasId.fillStyle = ranColor(min, max);

                // 保存绘制的状态
                canvasId.save();

                // context.translate(x,y);
                // x    添加到水平坐标(x)上的值
                // y    添加到垂直坐标(y)上的值
                // 偏移
                canvasId.translate(canvasW / num * i + canvasW / 20, 0);

                // 变换角度
                canvasId.rotate(ranNum(frMin, frMax) * Math.PI / 180);

                // context.fillText(text,x,y,maxWidth);
                // text    规定在画布上输出的文本。
                // x    开始绘制文本的 x 坐标位置(相对于画布)。
                // y    开始绘制文本的 y 坐标位置(相对于画布)。
                // maxWidth    可选。允许的最大文本宽度,以像素计。
                canvasId.fillText(char, 0, (canvasH + fs) / 2.5, canvasW / num);

                // 返回之前保存过的路径状态和属性
                ctx.restore();

                str += char;

            }

            // console.log(str);
            return str;

        }

        /**
         * 绘制背景
         * @param  {[String]} canvasId [canvas的id]
         * @param  {[Number]} canvasW  [canvas的width]
         * @param  {[Number]} canvasH  [canvas的height]
         * @param  {[Number]} min      [下限]
         * @param  {[Number]} max      [上限]
         */
        function drawBg(canvasId, canvasW, canvasH, min, max) {

            // 绘制canvas背景
            canvasId.fillStyle = ranColor(min, max);

            // 填充颜色
            canvasId.fillRect(0, 0, canvasW, canvasH);

        }

        /**
         * 绘制干扰 圆点
         * @param  {[String]} canvasId [canvas的id]
         * @param  {[Number]} canvasW  [canvas的width]
         * @param  {[Number]} canvasH  [canvas的height]
         * @param  {[Number]} num      [绘制的数量]
         * @param  {[Number]} r        [圆点半径]
         * @param  {[Number]} min      [下限]
         * @param  {[Number]} max      [上线]
         */
        function drawCircle(canvasId, canvasW, canvasH, num, r, min, max) {

            for (var i = 0; i < num; i++) {

                // 开始绘制 (拿起笔)
                canvasId.beginPath();

                // context.arc(x,y,r,sAngle,eAngle,counterclockwise); (绘制)
                // x    圆的中心的 x 坐标。
                // y    圆的中心的 y 坐标。
                // r    圆的半径。
                // sAngle    起始角,以弧度计。(弧的圆形的三点钟位置是 0 度)。
                // eAngle    结束角,以弧度计。
                // counterclockwise    可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。
                canvasId.arc(ranNum(0, canvasW), ranNum(0, canvasH), r, 0, 2 * Math.PI);

                // 填充颜色
                canvasId.fillStyle = ranColor(min, max);

                // 填充
                canvasId.fill();

                // 闭合绘制 (放开笔)
                canvasId.closePath();

            }

        }

        /**
         * 绘制干扰 线段
         * @param  {[String]} canvasId [canvas的id]
         * @param  {[Number]} canvasW  [canvas的width]
         * @param  {[Number]} canvasH  [canvas的height]
         * @param  {[Number]} num      [绘制的数量]
         * @param  {[Number]} min      [下限]
         * @param  {[Number]} max      [上线]
         */
        function drawLine(canvasId, canvasW, canvasH, num, min, max) {

            for (var i = 0; i < num; i++) {

                // 开始绘制 (拿起笔)
                canvasId.beginPath();

                // 绘制开始点
                canvasId.moveTo(ranNum(0, canvasW), ranNum(0, canvasH));

                // 绘制结束点
                canvasId.lineTo(ranNum(0, canvasW), ranNum(0, canvasH));

                canvasId.strokeStyle = ranColor(min, max);

                canvasId.stroke();

                canvasId.closePath();

            }

        }

        // 绘制验证码
        function drawCanvas() {

            // 清空canvas
            ctx.clearRect(0, 0, 200, 60);

            // 绘制背景
            drawBg(ctx, ctxW, ctxH, 200, 255);

            // 绘制干扰圆点
            drawCircle(ctx, ctxW, ctxH, 20, 5, 200, 255);

            // 绘制干扰线段
            drawLine(ctx, ctxW, ctxH, 20, 0, 255);

            // 绘制验证码
            var str = drawText(ctx, ctxW, ctxH, 4, 10, 50, -30, 30, 0, 100);

            return str;

        }

        drawCanvas();

        document.getElementById(&#39;check&#39;).onclick = drawCanvas;
    </script>
</body>

</html>

The above is the detailed content of HTML5 uses canvas to achieve verification code effect (code example). 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 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

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.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor