首页 > 技术文章 > canvas制作随机验证码

CooLLYP 2017-06-01 14:13 原文

看到人家彩色背景的验证码想测试一下:

创建html代码:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;box-sizing: border-box;">
    您的浏览器不支持 HTML5 canvas 标签。
</canvas>

创建相同js代码:

  function color(){
        var c1 = parseInt(Math.random()*10);
        var c2 = parseInt(Math.random()*10);
        var c3 = parseInt(Math.random()*10);
        var c4 = parseInt(Math.random()*10);
        var c5 = parseInt(Math.random()*10);
        var c6 = parseInt(Math.random()*10);
        return "#" + c1+ c2+ c3+ c4+ c5+ c6;  //创建随机颜色
    }

    function random(){
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        ctx.fillStyle='#000';
        ctx.fillRect(0,0,200,100); //这两句代码加上就不会出现重叠的情况? 不懂····
        for(var i = 0;i< 30;i++){
            ctx.beginPath();
            ctx.arc(parseInt(Math.random()*220),parseInt(Math.random()*110),3,0,2*Math.PI);
            ctx.fillStyle= color();
            ctx.stroke();
            ctx.fill();   //随便创建了一些五彩小圆点
        }
        // 创建渐变
        var grd=ctx.createLinearGradient(0,0,200,0);
        grd.addColorStop(0,"red");
        grd.addColorStop(1,"white");
        // 填充渐变
        ctx.fillStyle=grd;
        ctx.font="30px Arial";
        var rans = rand();     //创建了验证码
        ctx.fillText(rans,50,50); //实体
        console.log(rans)  //方便做判断或者其他
    }
    random();
    myCanvas.onclick = function(e){    //点击事件 触发 可以自定义元素
        e.preventDefault(); 
        random()
    }

1.先试用笨方法生成随机数字验证码:

创建数字:

function rand(){
        var num1 = parseInt(Math.random()*10);
        var num2 = parseInt(Math.random()*10);
        var num3 = parseInt(Math.random()*10);
        var num4 = parseInt(Math.random()*10);
        return num1 + " " +num2 + " " + num3+ " " + num4;    //如果验证码不是纯数字呢? 
    }

2.带有大小写字母 的随机验证码:

function rand(){
        var str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        var arr = str.split("");
        var sM = arr[Math.floor(Math.random()*arr.length)];
        var ss = "";  //定义一个变量存放 随机验证码的字符
        for(var i = 0;i< 4;i++){    //可以自定义几位验证码
            var sM = arr[Math.floor(Math.random()*arr.length)];
            ss +=sM;   //重新定义了一下随机数字 防止重复
        }
        return ss;
    }

实现效果如下:

推荐阅读