首页 > 编程语言 > JS如何生成随机验证码
2020
09-24

JS如何生成随机验证码

本文实例为大家分享了JS生成随机验证码的具体代码,供大家参考,具体内容如下

在网站中我们很常见到形形色色的验证码,今天我们来用JS来生成一个随机的二维码。

我们需要用到canvas来进行验证码的绘制

什么是Canvas

HTML5 的 canvas 元素使用 JavaScript 在网页上绘制图像。
画布是一个矩形区域,您可以控制其每一像素。
canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。

思路

我们要做的二维码首先要有随机的数字,其次就是要有随机的位置。

HTML

<canvas id="canvas" style="border: 1px solid red; width: 80px; height: 40px;">
</canvas>

JS

function getVerification() { //二维码
 var ctx = document.getElementById("canvas").getContext("2d");
 // 清空画布
 ctx.clearRect(0,0, 400, 400);
 // 设置字体
 ctx.font = "128px bold 黑体";
 // 设置垂直对齐方式
 ctx.textBaseline = "top";
 // 设置颜色
 ctx.fillStyle = randomColor();
 // 绘制文字(参数:要写的字,x坐标,y坐标)
 ctx.fillText(getRandomNum(10), 0, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 50, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 100, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 150, getRandomNum(50));
}

我们使用ctx.fillStyle = randomColor();来设置随机的颜色,每写一个数字换一个颜色,randomColoe()函数代码如下,可以随机生成十六进制颜色码。

function randomColor() {
 var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
 var colorArray = colorValue.split(",");
 var color = "#";
 for (var i = 0; i < 6; i++) {
 color += colorArray[Math.floor(Math.random() * 16)];
 }
 return color;
}

我们使用getRandomNum()来获取随机显示的数字和随机每次字体的y轴方向的位置。验证码的每个数字分别进行获取。传入的参数n来确定随机数范围。代码如下:

function getRandomNum(n){
 return parseInt(Math.random() * n); 
}

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>2</title>
</head>

<body>
 <canvas id="canvas" style="border: 1px solid red; width: 80px; height: 40px;"></canvas>
 <span id="yanzhengma"></span><button onclick="getVerification()">看不清</button>
 <script>
 function randomColor() {
 var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
 var colorArray = colorValue.split(",");
 var color = "#";
 for (var i = 0; i < 6; i++) {
 color += colorArray[Math.floor(Math.random() * 16)];
 }
 return color;
 }
 function getRandomNum(n){
 return parseInt(Math.random() * n); 
 }
 function getVerification() {
 var ctx = document.getElementById("canvas").getContext("2d");
 ctx.clearRect(0,0, 400, 400);
 // 设置字体
 ctx.font = "128px bold 黑体";
 // 设置垂直对齐方式
 ctx.textBaseline = "top";
 // 设置颜色
 ctx.fillStyle = randomColor();
 // 绘制文字(参数:要写的字,x坐标,y坐标)
 ctx.fillText(getRandomNum(10), 0, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 50, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 100, getRandomNum(50));
 ctx.fillStyle = randomColor();
 ctx.fillText(getRandomNum(10), 150, getRandomNum(50));
 }
 getVerification();
 </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧