Home > Web Front-end > JS Tutorial > Introduction to how to use canvas and js to generate verification codes

Introduction to how to use canvas and js to generate verification codes

巴扎黑
Release: 2017-08-16 11:59:10
Original
1233 people have browsed it
Verification codes are needed in many cases. The front-end verification code requires knowing the canvas knowledge points in Html5. The steps to generate the verification code are:
1. Generate a canvas
2. Generate a random number verification code
3. Generate interference lines in the canvas
4. Fill the verification code text into the canvas
5. Click on the canvas to change the verification code
Structure and style:
<canvas id="mycanvas" width=&#39;90&#39; height=&#39;40&#39;>
 您的浏览器不支持canvas,请换个浏览器试试~
</canvas>
  
<style>
#mycanvas{
 cursor: pointer;
}
</style>
Copy after login

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

This way you can write a more common verification code, of course There are also many areas that need to be optimized, such as the random colors of interference lines, the ability to add interference points, and the random colors of text at random positions, etc. Hurry up and try it~

The above is the detailed content of Introduction to how to use canvas and js to generate verification codes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template