在通常的登录界面我们都可以看到验证码,验证码的作用是检测是不是人在操作,防止机器等非人操作,防止数据库被轻而易举的攻破。
验证码一般用PHP和java等后端语言编写;
但是在前端,用canva或者SVG也可以绘制验证码;
直接上干货:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> canvas { border: 1px solid red; } </style> </head> <body> <canvas id="myCanvas" width="100" height="40"> 您的浏览器不支持canvas </canvas> </body> <script type="text/javascript"> var myCanvas = document.getElementById("myCanvas"); var context = myCanvas.getContext("2d"); //随机字符(透明度)(大小随机,位置随机); var strStore = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //随机函数 function roundNum(min, max) { return parseInt(Math.random() * (max - min) + min); } //文字内容部分: var str = ""; for(var i = 0; i < 5; i++) { context.beginPath(); //随机颜色(浅色:RGB - 200~250) var color = `rgb(${roundNum(0,255)},${roundNum(0,255)},${roundNum(0,255)})`; context.fillStyle = color; context.font = roundNum(20,30)+"px Arial"; context.textAlign = "center"; str = strStore[roundNum(0,strStore.length)]; context.fillText(str, 10 + 18 * i, roundNum(20,35)); } //10个左右的随机(长度随机,位置随机),干扰线 for(var j = 0; j < roundNum(5, 10); j++) { context.beginPath(); var color = `rgb(${roundNum(0,255)},${roundNum(0,255)},${roundNum(0,255)})`; context.strokeStyle = color; context.moveTo(roundNum(0, 100), roundNum(0, 40)); context.lineTo(roundNum(0, 100), roundNum(0, 40)); context.stroke(); } //干扰项:10个左右的随机(半径随机,位置随机),干扰圆 for(var j = 0; j < roundNum(5, 10); j++) { context.beginPath(); context.fillStyle = color; context.arc(roundNum(0, 100), roundNum(0, 40), roundNum(0, 5), Math.PI * 2 / (roundNum(1, 360)), Math.PI * 2 / (roundNum(1, 360))); context.fill(); } </script> </html>
结果如图:
至于要拿来咋用,就看大家高兴了。想怎么整这么整。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。