Home > Web Front-end > H5 Tutorial > How to use canvas to get the effect of verification code (source code attached)

How to use canvas to get the effect of verification code (source code attached)

不言
Release: 2018-09-15 16:00:26
Original
3067 people have browsed it

The content of this article is about how to use canvas to achieve the effect of verification code (source code attached). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We can see the verification code on the usual login interface. The function of the verification code is to detect whether a human is operating, prevent machines and other non-human operations, and prevent the database from being easily broken.

Verification codes are generally written in back-end languages ​​such as PHP and java.

But on the front end, you can also use canvas or SVG to draw the verification code.

The drawing verification code cannot be a simple random string, but there should be some interference items in the drawing interface:

For example: Interference line segment, Interference dots, Background, etc.

The canvas verification code interference item of this demo here is relatively simple.

You can see the distractors in this example in the illustration.

canvas verification code display effect:

Click to change (redraw) the verification code:

How to use canvas to get the effect of verification code (source code attached)

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

How to use canvas to get the effect of verification code (source code attached)

##Source 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>
Copy after login

Related recommendations:

php verification code simple function code (with renderings)

Introduction to how to use canvas and js to generate verification codes

The above is the detailed content of How to use canvas to get the effect of verification code (source code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template