溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

react如何實(shí)現(xiàn)圖片驗(yàn)證

發(fā)布時(shí)間:2022-12-27 10:24:47 來源:億速云 閱讀:178 作者:iii 欄目:web開發(fā)

這篇文章主要介紹“react如何實(shí)現(xiàn)圖片驗(yàn)證”,在日常操作中,相信很多人在react如何實(shí)現(xiàn)圖片驗(yàn)證問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”react如何實(shí)現(xiàn)圖片驗(yàn)證”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

react實(shí)現(xiàn)圖片驗(yàn)證的方法:1、打開相應(yīng)的react文件;2、通過“randomNum = (min, max) => {...}”方法生成一個(gè)隨機(jī)數(shù);3、通過“drawLine(ctx) {...}”方法繪制干擾線;4、使用“randomCode() {...}”方法隨機(jī)生成驗(yàn)證碼即可。

react實(shí)現(xiàn)圖片驗(yàn)證碼

效果如圖所示:

react如何實(shí)現(xiàn)圖片驗(yàn)證

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, // 默認(rèn)不顯示驗(yàn)證碼的錯(cuò)誤信息
  }
  componentWillMount() {
      this.canvas = React.createRef()
  }
  componentDidMount() {
      this.drawPic()
  }
  // 生成一個(gè)隨機(jī)數(shù)
  // eslint-disable-next-line arrow-body-style
  randomNum = (min, max) => {
      return Math.floor(Math.random() * (max - min) + min)
  }
  drawPic = () => {
      this.randomCode()
  }
  // 生成一個(gè)隨機(jī)的顏色
  // 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}, $)`
  }
  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)
      // 修改坐標(biāo)原點(diǎn)和旋轉(zhuǎn)角度
      ctx.translate(x, y)
      ctx.rotate(deg * Math.PI / 180)
      ctx.fillText(txt, 0, 0)
      // 恢復(fù)坐標(biāo)原點(diǎn)和旋轉(zhuǎn)角度
      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) {
      // 繪制干擾點(diǎn)
      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: '',
      });
  }
  // 輸入驗(yàn)證碼
  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
          })
      }
  }
  // 隨機(jī)生成驗(yàn)證碼
  randomCode() {
    let random = ''
    // 去掉了I l i o O,可自行添加
    const str = 'QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm1234567890'
    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('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;
    return (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ width: 300 }}>
          <Form.Item className='for-form'>
            {getFieldDecorator('sendcode', {
                rules: [
                  { required: true, message: '請(qǐng)輸入校驗(yàn)碼!' },
                  {
                    validator: (rule, value, callback) => {
                      if (value) {
                        if(value.toLowerCase()===this.state.code.toLowerCase()){
                              callback()                                                                    
                              this.setState({
                                sendcode: value,
                                showError: false
                              })
                        } else {
                            callback('請(qǐng)輸入正確的驗(yàn)證碼')
                            this.setState({
                                showError: true
                            })
                        }
                      } else {
                        callback()
                      }
                    }
                  }
                ],
                  })(
                  <Input
                      prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                      onChange={this.changeCode}
                      placeholder="請(qǐng)輸入校驗(yàn)碼"
                  />
                )}
          </Form.Item>
        </div>
        <div>
            <canvas
              onClick={this.reloadPic}
              ref={this.canvas}
              width='100'
              height='30'>
            </canvas>
        </div>
      </div>
    )
  }
}
const WrappedRegistrationForm = Form.create()(OperationalDataManagement);
export default WrappedRegistrationForm;

到此,關(guān)于“react如何實(shí)現(xiàn)圖片驗(yàn)證”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI