1. /**生成一个随机数**/
    2. function randomNum(min,max){
    3. return Math.floor(Math.random()*(max-min)+min);
    4. }
    5. /**生成一个随机色**/
    6. function randomColor(min,max){
    7. var r = randomNum(min,max);
    8. var g = randomNum(min,max);
    9. var b = randomNum(min,max);
    10. return "rgb("+r+","+g+","+b+")";
    11. }
    12. drawPic();
    13. document.getElementById("changeImg").onclick = function(e){
    14. e.preventDefault();
    15. drawPic();
    16. } /**绘制验证码图片**/
    17. function drawPic(){
    18. var canvas=document.getElementById("canvas");
    19. var width=canvas.width;
    20. var height=canvas.height;
    21. var ctx = canvas.getContext('2d');
    22. ctx.textBaseline = 'bottom';
    23. /**绘制背景色**/
    24. ctx.fillStyle = randomColor(180,240);
    25. //颜色若太深可能导致看不清
    26. ctx.fillRect(0,0,width,height);
    27. /**绘制文字**/
    28. var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
    29. for(var i=0; i<4; i++){
    30. var txt = str[randomNum(0,str.length)];
    31. ctx.fillStyle = randomColor(50,160);
    32. //随机生成字体颜色
    33. ctx.font = randomNum(15,40)+'px SimHei';
    34. //随机生成字体大小
    35. var x = 10+i*25;
    36. var y = randomNum(25,45);
    37. var deg = randomNum(-45, 45);
    38. //修改坐标原点和旋转角度
    39. ctx.translate(x,y);
    40. ctx.rotate(deg*Math.PI/180);
    41. ctx.fillText(txt, 0,0);
    42. //恢复坐标原点和旋转角度
    43. ctx.rotate(-deg*Math.PI/180);
    44. ctx.translate(-x,-y); }
    45. /**绘制干扰线**/
    46. for(var i=0; i<8; i++){
    47. ctx.strokeStyle = randomColor(40,180);
    48. ctx.beginPath();
    49. ctx.moveTo( randomNum(0,width),randomNum(0,height) );
    50. ctx.lineTo( randomNum(0,width),randomNum(0,height) );
    51. ctx.stroke();
    52. }
    53. /**绘制干扰点**/
    54. for(var i=0; i<100; i++){
    55. ctx.fillStyle = randomColor(0,255);
    56. ctx.beginPath();
    57. ctx.arc(randomNum(0,width),randomNum(0,height), 1, 0, 2*Math.PI);
    58. ctx.fill();
    59. }
    60. }