各个方法

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

完整代码 方便复制粘贴

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={{ width: '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);

在React中随机生成图形验证码的更多相关文章

  1. ASP.NET中如何生成图形验证码

    通常生成一个图形验证码主要 有3个步骤: (1)随机产生一个长度为N的随机字符串,N的值可由开发可由开发人员自行设置.该字符串可以包含数字.字母等. (2)将随机生成的字符串创建成图片,并显示. (3 ...

  2. java生成图形验证码

    效果图 import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.Buf ...

  3. C#生成图形验证码

    先看效果: 再上代码 public class CaptchaHelper { private static Random rand = new Random(); private static in ...

  4. PHP5 GD库生成图形验证码(汉字)

    PHP5 GD库生成图形验证码且带有汉字的实例分享. 1,利用GD库函数生成图片,并在图片上写指定字符imagecreatetruecolor 新建一个真彩色图像imagecolorallocate ...

  5. PHP5生成图形验证码(有汉字)

    利用PHP5中GD库生成图形验证码 类似于下面这样 1.利用GD库函数生成图片,并在图片上写指定字符 imagecreatetruecolor   新建一个真彩色图像      imagecolora ...

  6. python 生成图形验证码

    文章链接:https://mp.weixin.qq.com/s/LYUBRNallHcjnhJb1R3ZBg 日常在网站使用过程中经常遇到图形验证,今天准备自己做个图形验证码,这算是个简单的功能,也适 ...

  7. asp.net 生成图形验证码(字母和数字混合)

    验证码技术是网站开发过程中比较重要的技术,可以防止非法人员利用注册机或者登陆工具来攻击我们的网站.下面是效果图: 具体实现方法如下: 1.主要思路是:引用Using System.Drawing命名空 ...

  8. (转)Android 之生成图形验证码

    import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; impor ...

  9. 【Java】生成图形验证码

    本章介绍一个能生成比较好看的图形验证码类 生成验证码工具类 package com.util; import java.awt.Color; import java.awt.Font; import ...

随机推荐

  1. Python语言——map/reduce的用法

    Python内建了map()和reduce()函数. 如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Processing on Large Clus ...

  2. base64,base32bit加密解密

    import base64 str='admin' str=str.encode('utf-8') #加密 bs64=base64.b64encode(str) #解密 debs64=base64.b ...

  3. 「CQOI2016」不同的最小割

    「CQOI2016」不同的最小割 传送门 建出最小割树,把每一个点对的最小割抠出来 \(\text{unique}\) 一下就好了. 参考代码: #include <algorithm> ...

  4. ios中时间倒计时

    博客地址 https://github.com/sundayios/SQCountTimeDown.git

  5. git切换分支导致代码丢失找回(git reflog找回错误的重置)

    1.使用git reflog查看日志 2.切换到丢失的分支 3. 创建一个临时分支  如(diff),并切换到dev(原分支),然后合并diff到dev分支 4.查看状态 5.强制合并,然后提交到de ...

  6. 读取npz,并显示图像

    import numpy as npimport osimport matplotlib.pyplot as pltimport sysimport cv2 a = np.load('/home/wg ...

  7. 关于盒模型的外边距padding和内边距margin

    边框border属性值  solid实线   dashed虚线   dotted点线   double双实线 /* 内边距 */padding:20px 30px 30px 30px;若有四个值代表  ...

  8. FFmpeg——AVCodec,AVCodecContext,AVCodecParameters 辨析

    先贴上雷神的一张FFmpeg关键结构体之间的关系图: 再看雷神的分析: 每个AVStream存储一个视频/音频流的相关数据: 每个AVStream对应一个AVCodecContext,存储该视频/音频 ...

  9. Python 基础之import导包

    首先需要将import内容建立一个大概如下层级的包: 以黑色框为第一级,蓝色框为第二级,棕色框为第三级,红色框为第四级 一.import 引入初识 首先在module.py写入代码如下: xboy = ...

  10. 2019年的代码都写完了吗?不如做个Python进度条看看还剩多少

    我们都知道,进度条是用来直观展示流程所需时间的优秀工具,以免我们担心流程会突然挂掉,而且我们可以用它来预测代码运行是否正常,借助进度条,每个人都能直观地看到脚本最新的进展情况. 如果你之前没用过进度条 ...