The task of
Work is to do a verification code with interference items, the first thought is the use of H5 canvas to achieve.
would like to copy a piece of code directly online, but many do not meet the requirements, simply write their own, the code is as follows.
<canvas class= "codeimg" id= "codeimg" style= "width:120px;height:36px" > Your Browser does not support the canvas
Element.
</canvas> <script type= "Text/javascript" > var code = "";
$ (). Ready (function () {//assigns the return value to code code = Createcode ();
Click the canvas image to replace the verification code $ ("#codeimg"). Click (function () {createcode ();
}); /* Random character function */function rand () {//Remove i,i,l,o,o and other easily confusing letters var str= "ABCDEFGHJKMNPQRSTUVWXYZABCDEFGHJK
LMNPQRSTUVWXYZ 0123456789 ";
Separates a string into an array of Var arr=str.split ("");
Random characters between [0,56] var rannum=math.floor (Math.random () *57);
var captcha=arr[rannum];
return captcha;
}/* Random interference line function */function drawline (canvas, context) {//If Beginpath is omitted, the number of lines of interference is accumulated per click of CAPTCHA
Context.beginpath (); The start and end point are randomly context.move within the canvas's wide heightTo (Math.floor (Math.random () * canvas.width), Math.floor (Math.random () * canvas.height));
Context.lineto (Math.floor (Math.random () * canvas.width), Math.floor (Math.random () * canvas.height));
Context.linewidth = 1;
Context.strokestyle = ' #275DB3 ';
Context.stroke ();
}/* Generate Verification Code */function Createcode () {////Generate code first to clear it to prevent overlay code = "";
var canvas = document.getElementById ("codeimg");
var context = Canvas.getcontext ("2d");
Context.strokestyle = "#FFF";
Context.strokerect (0, 0, canvas.width, canvas.height);
Generate the interference line, the amount is arbitrary for (var i = 0; i < i++) {DrawLine (canvas, context); }//Loop generates 5-bit verification code for (var k = 0; k < 5; k++) {context.font= ' 76px Arial '
;
Save the initial state context.save (); Obtain a random number of 1 to 1 var RA = 1-math.random () * * *;
Get random tilt angle var angle = RA/8;
var rannum = rand ();
Spin-generated random character context.rotate (angle);
Fill in the random number text generated by rand () into the canvas, and note the x-coordinate context.filltext (rannum,20+45*k,100);
Restore the initial state so that the next cycle context.restore ();
Code + = Rannum;
}//Returns the generated verification code string return code; }} </script>
Where the code variable is used to verify that the user input value is consistent with the verification code, and as a condition for login verification, it is simply not posted.
finally look at the effect diagram: