1. 程式人生 > >H5 +JavaScript生成驗證碼

H5 +JavaScript生成驗證碼

H5 +JavaScript實現簡單的驗證碼功能

在學習h5的過程中,為了增加使用的熟練度所做的小練習,還有許多不足之處,希望和大家一起討論。

html程式碼
<canvas id="canvas1"  style="margin-left: 200px;"></canvas><br />
<button id="btnRefresh" style="position: relative;left: 200px;">看不清,重新整理一下</button>

js程式碼

/*定義函式生成隨機顏色*/
function colorRandom()
{
var r = Math.floor(Math.random()*256); var g = Math.floor(Math.random()*256); var b = Math.floor(Math.random()*256); return "rgb("+ r + ","+ g +","+ b+")"; } /*生成隨機數*/ var canvas,context; function getYZ(){ canvas = document.getElementById("canvas1"); context = canvas.getContext('2d'
); canvas.width = 200; canvas.height = 100; context.beginPath(); context.fillStyle = colorRandom();//顯示驗證碼區域的背景色 context.rect(0,55,100,40); context.fill(); for(var i = 0;i<4;i++){ context.font =( Math.random()*20+16)+"px 微軟雅黑";//數字隨機大小 context.fillStyle = colorRandom();//數字顏色
context.fillText(parseInt(Math.random()*9), 20*i,90); //0-9的隨機數 } } /*實現*/ window.onload = function(){ getYZ(); document.getElementById("btnRefresh").onclick = function(){ getYZ(); } }