<!DOCTYPE html>
Document
验证码
<br> /*生成4位随机数*/<br> function rand() {<br> var str = "abcdefghijklmnopqrstuvwxyz0123456789";<br> var arr = str.split("");<br> var validate = "";<br> var ranNum;<br> for (var i = 0; i < 4; i++) {<br> ranNum = Math.floor(Math.random() * 36); //随机数在[0,35]之间<br> validate += arr[ranNum];<br> }<br> return validate;<br> }<br> /*干扰线的随机x坐标值*/<br> function lineX() {<br> var ranLineX = Math.floor(Math.random() * 90);<br> return ranLineX;<br> }<br> /*干扰线的随机y坐标值*/<br> function lineY() {<br> var ranLineY = Math.floor(Math.random() * 40);<br> return ranLineY;<br> }<br> function clickChange() {<br> var mycanvas = document.getElementById('mycanvas');<br> var cxt = mycanvas.getContext('2d');<br> cxt.fillStyle = '#000';<br> cxt.fillRect(0, 0, 90, 40);<br> /*生成干扰线20条*/<br> for (var j = 0; j < 20; j++) {<br> cxt.strokeStyle = '#fff';<br> cxt.beginPath(); //若省略beginPath,则每点击一次验证码会累积干扰线的条数<br> cxt.moveTo(lineX(), lineY());<br> cxt.lineTo(lineX(), lineY());<br> cxt.lineWidth = 0.5;<br> cxt.closePath();<br> cxt.stroke();<br> }<br> cxt.fillStyle = 'red';<br> cxt.font = 'bold 20px Arial';<br> cxt.fillText(rand(), 25, 25); //把rand()生成的随机数文本填充到canvas中<br><br> }<br> clickChange();<br> /*点击验证码更换*/<br> mycanvas.onclick = function (e) {<br> e.preventDefault(); //阻止鼠标点击发生默认的行为<br> clickChange();<br> };<br>