zoukankan      html  css  js  c++  java
  • canvas验证码制作

    <canvas id="canvas" width="120" height="40"></canvas>
    <script>
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    draw();
    canvas.onclick = function () {
    context.clearRect(0, 0, 120, 40); //清除画布
    draw();
    }
    function getColor() {
    // 0 - 255之间的随机数
    var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);
    return `rgb(${r},${g},${b})`;
    // return "rgb(" + r + "," + g + "," + b + ")";
    }
    function draw() {
    context.strokeRect(0, 0, 120, 40); //绘制一个描边矩形
     
    //随机绘制8条直线, 起始坐标 在矩形任何区域, 结束坐标在矩形任何区域
    for (var i = 0; i < 8; i++) {
    context.beginPath();
    context.moveTo(Math.random() * 120, Math.random() * 40);
    context.lineTo(Math.random() * 120, Math.random() * 40);
    context.strokeStyle=getColor();
    context.stroke();
    }
    //20个小点, 颜色随机
    for (var i = 0; i < 20; i++) {
    context.beginPath();
    var x = Math.random() * 120;
    var y = Math.random() * 40;
    context.arc(x,y,1,0,360 * (Math.PI/180));
    context.fillStyle=getColor();
    context.fill();
    }

    var aCode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    for (var i = 0; i < 4; i++) {
    context.save();
    var x = 20 + i * 20; //每个文字间隔是 20个像素
    var y = 20 + 10 * Math.random(); //垂直坐标是 20 - 30个像素之间

    var index = Math.floor(Math.random() * aCode.length);//随机索引值
    var txt = aCode[index];
    context.font = "bold 25px 微软雅黑";
    context.fillStyle=getColor();
    //水平和垂直方向的位移
    context.translate(x,y);
    //对文字的旋转
    var deg=90*Math.random()* (Math.PI/180);
    context.rotate(deg);
    //写入文字
    context.fillText(txt, 0, 0);
    context.restore();
     
    }
    }
  • 相关阅读:
    asp.net BS拖拽工作流设计及研发(附Demo源码)
    分享NOSQL开发实战
    jQuery插件开发实战
    asp.net搜索引擎(网络爬虫)设计及研发
    asp.net 统一认证及单点登录平台解决方案系列<一>
    ubuntu安装python的psycopg2库时报错
    记一次工作中的小坑(关于celery)
    ssh错误 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
    使用nobody运行redis
    安装python图像处理库PIL
  • 原文地址:https://www.cnblogs.com/laneyfu/p/14352619.html
Copyright © 2011-2022 走看看