zoukankan      html  css  js  c++  java
  • 在React中随机生成图形验证码

    各个方法

    在输入框中定义一个位置存放图形

    完整代码 方便复制粘贴

    import React, { Component } from 'react';
    import styles from './leftLogin.scss';
    import { withRouter } from 'dva/router';
    import { connect } from 'dva';
    import { Form, Icon, Input, Button, Checkbox } from 'antd';

    @connect(({ login }) => ({
    login,
    }))

    class leftLogin extends Component {
    constructor(props) {
    super(props);
    this.state = {
    code: '',
    codeLength: 4,
    fontSizeMin: 20,
    fontSizeMax: 22,
    backgroundColorMin: 240,
    backgroundColorMax: 250,
    colorMin: 10,
    colorMax: 20,
    lineColorMin: 40,
    lineColorMax: 180,
    contentWidth: 96,
    contentHeight: 38,
    showError: false, // 默认不显示验证码的错误信息
    };
    }

    UNSAFE_componentWillMount() {
    this.canvas = React.createRef();
    }

    componentDidMount() {
    this.drawPic();
    }

    // 点击登录按钮
    handleSubmit = e => {
    e.preventDefault();
    this.drawPic();
    this.props.form.validateFields((err, values) => {
    if (!err && this.state.showError !== true) {
    // 调登录接口
    const { dispatch } = this.props;
    dispatch({
    type: 'login/login',
    payload: {
    account: values.username,
    pwd: values.password
    }
    })
    this.props.form.setFieldsValue({
    sendcode: '',
    });
    this.setState({
    showError: false
    })
    }
    });
    }

    // 跳转到忘记密码页
    forget = () => {
    this.props.history.push('/forget')
    }

    // 跳转到注册页
    regist = () => {
    this.props.history.push('/regist')
    }

    // 生成一个随机数
    randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
    }

    drawPic = () => {
    this.randomCode()
    }

    // 生成一个随机的颜色
    randomColor(min, max) {
    const r = this.randomNum(min, max)
    const g = this.randomNum(min, max)
    const b = this.randomNum(min, max)
    return rgb(${r}, ${g}, ${b})
    }

    drawText(ctx, txt, i) {
    ctx.fillStyle = this.randomColor(this.state.colorMin, this.state.colorMax)
    let fontSize = this.randomNum(this.state.fontSizeMin, this.state.fontSizeMax)
    ctx.font = fontSize + 'px SimHei'
    let padding = 10;
    let offset = (this.state.contentWidth - 40) / (this.state.code.length - 1)
    let x = padding;
    if (i > 0) {
    x = padding + (i * offset)
    }
    let y = this.randomNum(this.state.fontSizeMax, this.state.contentHeight - 5)
    if (fontSize > 40) {
    y = 40
    }
    let deg = this.randomNum(-10, 10)
    // 修改坐标原点和旋转角度
    ctx.translate(x, y)
    ctx.rotate(deg * Math.PI / 180)
    ctx.fillText(txt, 0, 0)
    // 恢复坐标原点和旋转角度
    ctx.rotate(-deg * Math.PI / 180)
    ctx.translate(-x, -y)
    }

    drawLine(ctx) {
    // 绘制干扰线
    for (let i = 0; i < 1; i++) {
    ctx.strokeStyle = this.randomColor(this.state.lineColorMin, this.state.lineColorMax)
    ctx.beginPath()
    ctx.moveTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
    ctx.lineTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight))
    ctx.stroke()
    }
    }

    drawDot(ctx) {
    // 绘制干扰点
    for (let i = 0; i < 100; i++) {
    ctx.fillStyle = this.randomColor(0, 255)
    ctx.beginPath()
    ctx.arc(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight), 1, 0, 2 * Math.PI)
    ctx.fill()
    }
    }

    reloadPic = () => {
    this.drawPic()
    this.props.form.setFieldsValue({
    sendcode: '',
    });
    }

    // 输入验证码
    changeCode = e => {

    if (e.target.value.toLowerCase() !== '' && e.target.value.toLowerCase() !== this.state.code.toLowerCase()) {
      this.setState({
        showError: true
      })
    } else if (e.target.value.toLowerCase() === '') {
      this.setState({
        showError: false
      })
    } else if (e.target.value.toLowerCase() === this.state.code.toLowerCase()) {
      this.setState({
        showError: false
      })
    }
    

    }

    // 随机生成验证码
    randomCode() {
    let random = ''
    // 去掉了I l i o O
    const str = 'QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm1234567890'
    for (let i = 0; i < this.state.codeLength; i++) {
    let index = Math.floor(Math.random() * 57);
    random += str[index];
    }
    this.setState({
    code: random
    },()=>{
    let canvas = this.canvas.current;
    let ctx = canvas.getContext('2d')
    ctx.textBaseline = 'bottom'
    // 绘制背景
    ctx.fillStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax)
    ctx.fillRect(0, 0, this.state.contentWidth, this.state.contentHeight)
    // 绘制文字
    for (let i = 0; i < this.state.code.length; i++) {
    this.drawText(ctx, this.state.code[i], i)
    }
    this.drawLine(ctx)
    this.drawDot(ctx)
    })
    }

    render() {
    const { getFieldDecorator } = this.props.form;
    const suffix =





    return (

    <Form onSubmit={this.handleSubmit} style={{ '398px', margin: '0 auto', fontSize: '12px' }}>
    <Form.Item>
    {getFieldDecorator('username', {
    rules: [{ required: true, message: '请输入用户名!' }, {
    pattern: /^1[3456789]\d{9}$/,
    message: '手机号格式不正确'
    }],
    })(
    <Input
    size="large"
    prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
    placeholder="请输入手机号"
    />,
    )}
    </Form.Item>
    <Form.Item>
    {getFieldDecorator('password', {
    rules: [{ required: true, message: '请输入密码!' }, {
    pattern: /^.{6,}$/,
    message: '密码格式不正确(不得低于6位)'
    }],
    })(
    <Input
    size="large"
    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
    type="password"
    placeholder="请输入密码"
    />,
    )}
    </Form.Item>
    <Form.Item>
    {getFieldDecorator('sendcode', {
    rules: [{ required: true, message: '请输入校验码!' },],
    })(
    <Input
    size="large"
    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
    suffix={suffix}
    onChange={this.changeCode}
    placeholder="请输入校验码"
    />,
    )}
    {
    this.state.showError ?

    请输入正确的验证码

    : null
    }
    </Form.Item>

              <Form.Item className={this.state.showError ? styles.inputBottom : ''}>
                {getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: true,
                })(<Checkbox>7天内免登录</Checkbox>)}
                <a className={styles.forget} onClick={this.forget}>
                  忘记密码
                </a>
                <Button
                  size="large"
                  type="primary"
                  htmlType="submit"
                  className={styles.button}
                >
                  登录
                </Button>
                <a onClick={this.regist}>新用户注册</a>
              </Form.Item>
            </Form>
      </div>
    );
    

    }
    }

    const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(leftLogin);

    export default withRouter(WrappedNormalLoginForm);

    查看全文
  • 相关阅读:
    Android之BroadcastReceiver1
    contentprovider提供程序间共享数据的统一接口
    Android之访问下载文件
    Android之SQLite
    Android之Handler
    sql server异地备份数据库
    Android常用控件
    Android学习笔记02
    Android学习笔记01
    java多线程的使用2
  • 原文地址:https://www.cnblogs.com/zpsakura/p/11375864.html
  • 最新文章
  • spring boot常用注解
    Java Date 时分秒置0
    linux cpu 100% 脚本
    自动升级脚本
    智能合约 运算
    智能合约 拍卖
    以太坊私有链
    ntp测试
    docker 清理命令
    spring boot application.properties
  • 热门文章
  • iptables端口转发
    android之AutoCompleteTextView控件用法
    android之Spinner控件用法
    android之datepicker控件用法
    Android学习路线
    WebView用法
    Android之Service
    android-Service和Thread的区别
    控制WIFI状态
    Android之BroadcastReceiver 监听系统广播
Copyright © 2011-2022 走看看

代做工资流水公司襄阳离职证明价格荆州公司银行流水代办保定企业对公流水多少钱惠州流水多少钱重庆制作房贷收入证明九江做日常消费流水青岛制作银行流水柳州流水办理唐山打个人银行流水深圳工资证明图片泰州办薪资银行流水绍兴在职证明费用漳州自存银行流水图片赣州对公账户流水费用常州办入职银行流水石家庄工资代付流水费用佛山流水单价格泰州查在职证明盐城银行流水账单代开吉林自存银行流水多少钱常州银行流水电子版代开佛山银行流水账报价苏州在职证明办理兰州企业对公流水公司宿迁个人银行流水样本绵阳入职银行流水制作潍坊工资流水app截图报价泰安工资银行流水报价保定查企业对私流水湛江查询薪资银行流水香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声卫健委通报少年有偿捐血浆16次猝死汪小菲曝离婚始末何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言男子被猫抓伤后确诊“猫抓病”周杰伦一审败诉网易中国拥有亿元资产的家庭达13.3万户315晚会后胖东来又人满为患了高校汽车撞人致3死16伤 司机系学生张家界的山上“长”满了韩国人?张立群任西安交通大学校长手机成瘾是影响睡眠质量重要因素网友洛杉矶偶遇贾玲“重生之我在北大当嫡校长”单亲妈妈陷入热恋 14岁儿子报警倪萍分享减重40斤方法杨倩无缘巴黎奥运考生莫言也上北大硕士复试名单了许家印被限制高消费奥巴马现身唐宁街 黑色着装引猜测专访95后高颜值猪保姆男孩8年未见母亲被告知被遗忘七年后宇文玥被薅头发捞上岸郑州一火锅店爆改成麻辣烫店西双版纳热带植物园回应蜉蝣大爆发沉迷短剧的人就像掉进了杀猪盘当地回应沈阳致3死车祸车主疑毒驾开除党籍5年后 原水城县长再被查凯特王妃现身!外出购物视频曝光初中生遭15人围殴自卫刺伤3人判无罪事业单位女子向同事水杯投不明物质男子被流浪猫绊倒 投喂者赔24万外国人感慨凌晨的中国很安全路边卖淀粉肠阿姨主动出示声明书胖东来员工每周单休无小长假王树国卸任西安交大校长 师生送别小米汽车超级工厂正式揭幕黑马情侣提车了妈妈回应孩子在校撞护栏坠楼校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变老人退休金被冒领16年 金额超20万西藏招商引资投资者子女可当地高考特朗普无法缴纳4.54亿美元罚金浙江一高校内汽车冲撞行人 多人受伤

代做工资流水公司 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化