首頁  >  文章  >  web前端  >  react怎麼實作圖片驗證

react怎麼實作圖片驗證

藏色散人
藏色散人原創
2022-12-21 15:27:282675瀏覽

react實現圖片驗證的方法:1、開啟對應的react檔案;2、透過「randomNum = (min, max) => {...}」方法產生一個隨機數;3、透過“drawLine(ctx) {...}”方法繪製幹擾線;4、使用“randomCode() {...}”方法隨機產生驗證碼即可。

react怎麼實作圖片驗證

本教學操作環境:Windows10系統、react18版、Dell G3電腦。

react怎麼實作圖片驗證?

react實作圖片驗證碼

效果如圖所示:

react怎麼實作圖片驗證

import React, { Component } from 'react'
import { Icon, Input, Form } from 'antd';
class OperationalDataManagement extends Component {
  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, // 默认不显示验证码的错误信息
  }
  componentWillMount() {
      this.canvas = React.createRef()
  }
  componentDidMount() {
      this.drawPic()
  }
  // 生成一个随机数
  // eslint-disable-next-line arrow-body-style
  randomNum = (min, max) => {
      return Math.floor(Math.random() * (max - min) + min)
  }
  drawPic = () => {
      this.randomCode()
  }
  // 生成一个随机的颜色
  // eslint-disable-next-line react/sort-comp
  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)
      const fontSize = this.randomNum(this.state.fontSizeMin, this.state.fontSizeMax)
      ctx.font = fontSize + 'px SimHei'
      const padding = 10;
      const 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
      }
      const 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: &#39;&#39;,
      });
  }
  // 输入验证码
  changeCode = e => {
      if (e.target.value.toLowerCase() !== &#39;&#39; && e.target.value.toLowerCase() !== this.state.code.toLowerCase()) {
          this.setState({
              showError: true
          })
      } else if (e.target.value.toLowerCase() === &#39;&#39;) {
          this.setState({
              showError: false
          })
      } else if (e.target.value.toLowerCase() === this.state.code.toLowerCase()) {
          this.setState({
              showError: false
          })
      }
  }
  // 随机生成验证码
  randomCode() {
    let random = &#39;&#39;
    // 去掉了I l i o O,可自行添加
    const str = &#39;QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm1234567890&#39;
    for (let i = 0; i < this.state.codeLength; i++) {
        const index = Math.floor(Math.random() * 57);
        random += str[index];
    }
    this.setState({
        code: random
    }, () => {
        const canvas = this.canvas.current;
        const ctx = canvas.getContext(&#39;2d&#39;)
        ctx.textBaseline = &#39;bottom&#39;
        // 绘制背景
        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;
    return (
      <div style={{ display: &#39;flex&#39;, alignItems: &#39;center&#39; }}>
        <div style={{ width: 300 }}>
          <Form.Item className=&#39;for-form&#39;>
            {getFieldDecorator(&#39;sendcode&#39;, {
                rules: [
                  { required: true, message: &#39;请输入校验码!&#39; },
                  {
                    validator: (rule, value, callback) => {
                      if (value) {
                        if(value.toLowerCase()===this.state.code.toLowerCase()){
                              callback()                                                                    
                              this.setState({
                                sendcode: value,
                                showError: false
                              })
                        } else {
                            callback(&#39;请输入正确的验证码&#39;)
                            this.setState({
                                showError: true
                            })
                        }
                      } else {
                        callback()
                      }
                    }
                  }
                ],
                  })(
                  <Input
                      prefix={<Icon type="lock" style={{ color: &#39;rgba(0,0,0,.25)&#39; }} />}
                      onChange={this.changeCode}
                      placeholder="请输入校验码"
                  />
                )}
          </Form.Item>
        </div>
        <div>
            <canvas
              onClick={this.reloadPic}
              ref={this.canvas}
              width=&#39;100&#39;
              height=&#39;30&#39;>
            </canvas>
        </div>
      </div>
    )
  }
}
const WrappedRegistrationForm = Form.create()(OperationalDataManagement);
export default WrappedRegistrationForm;

#推薦學習:《react影片教學

以上是react怎麼實作圖片驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn