JS如何生成随机验证码

JS如何生成随机验证码

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

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

什么是Canvas

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

思路

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

HTML

<canvas> </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 content="width=device-width, initial-scale=1.0"> <title>2</title> </head> <body> <canvas></canvas> <span></span><button>看不清</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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/bc725cfcd1cda80c752033f07ef40786.html