在通常的登錄界面我們都可以看到驗證碼,驗證碼的作用是檢測是不是人在操作,防止機器等非人操作,防止數據庫被輕而易舉的攻破。
驗證碼一般用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>
結果如圖:
至于要拿來咋用,就看大家高興了。想怎么整這么整。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答