本篇文章给大家分享的是有关使用canvas怎么实现一个图形验证码功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
<!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>
结果如图:
以上就是使用canvas怎么实现一个图形验证码功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网行业资讯频道。