zoukankan      html  css  js  c++  java
  • 【重点突破】——Canvas技术绘制随机改变的验证码

    一、引言

    本文主要是我在学习Canvas技术绘图时的一个小练习,绘制随机改变的验证码图片,虽然真正的项目里不这么做,但这个练习是一个掌握Canvas技术很好的综合练习。(真正的项目中验证码图片使用服务器端技术,而不是客户端技术。)

    二、要求

    • 画布背景颜色随机(浅色)  ctx.fillRect()
    • 文字内容随机、大小随机、颜色随机(深色)、旋转角度随机
    • 6条随机干扰线(深色),处于文字上方
    • 50个杂色点(半径为1为园),处于文字上方

    三、实现

     注意:反复使用的功能,比如求随机数Math.floor(Math.random()*(max-min)+min);要封装为函数或插件,这样方便反复调用。

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
       <h1>使用Canvas绘图</h1>
       <canvas id="c1"></canvas>
    
       <script>
           var w = 120;
           var h = 30;
           c1.width = w;
           c1.height = h;
    
           var ctx = c1.getContext('2d');
    
           //填充背景颜色
           ctx.fillStyle = rc(180,230);
           ctx.fillRect(0,0,w,h);
           ctx.textBaseline = 'top';
    
           //绘制随机的字符
           var pool = 'ABCDEFGHJKLMNPQRSTUVWXY3456789';
           for(var i=0;i<4;i++){
               var c = pool[rn(0,pool.length)];//下标随机取出
               var fs = rn(15,35);//随机的字体大小
               var deg = rn(-45,45);//随机的旋转角度
               ctx.font = fs+'px SimHei';
               ctx.fillStyle = rc(80,180);
               ctx.save();//存盘
               ctx.translate(30*i+15, 15);
               ctx.rotate(deg*Math.PI/180);
               ctx.fillText(c,-15+5,-15);
               ctx.restore();//恢复存盘
           }
    
           //绘制6条干扰线
           for(var i=0;i<6;i++){
               ctx.strokeStyle = rc(0,255);
               ctx.beginPath();
               ctx.moveTo(rn(0, w), rn(0, h));
               ctx.lineTo(rn(0, w), rn(0, h));
               ctx.stroke();
           }
    
           //绘制50个杂色点-半径为0.5的圆形,填充
           for(var i=0;i<50;i++){
               ctx.fillStyle = rc(0,255);
               ctx.beginPath();
               ctx.arc(rn(0,w), rn(0,h),  0.5, 0, 2*Math.PI);
               ctx.fill();
           }
    
           //random number:返回指定范围内的随机整数
           function rn(min,max){
               var n = Math.floor(Math.random()*(max-min)+min);
               return n;
           }
           //random color:返回指定范围内的随机颜色
           //形如:rgb(x,x,x)
           function rc(min, max){
               var r = rn(min, max);
               var g = rn(min, max);
               var b = rn(min, max);
               return `rgb(${r},${g},${b})`;
           }
       </script>
    </body>
    </html>

     效果:


     注:转载请注明出处 

  • 相关阅读:
    python基础
    HTTP长连接和短连接及应用情景
    HTTP和HTTPS的区别
    python---重建二叉树
    python---替换空格
    python---二维数组的查找
    python---从尾到头打印链表
    python---反转链表
    python---两个栈实现一个队列
    python---二分查找的实现
  • 原文地址:https://www.cnblogs.com/ljq66/p/7620472.html
Copyright © 2011-2022 走看看