欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react的滑動(dòng)圖片驗(yàn)證碼組件的示例代碼

 更新時(shí)間:2019年02月27日 10:59:22   作者:darcrand  
這篇文章主要介紹了react的滑動(dòng)圖片驗(yàn)證碼組件的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

業(yè)務(wù)需求,需要在系統(tǒng)登陸的時(shí)候,使用“滑動(dòng)圖片驗(yàn)證碼”,來驗(yàn)證操作的不是機(jī)器人。

效果圖

使用方式

在一般的頁面組件引用即可。onReload這個(gè)函數(shù)一般是用來請(qǐng)求后臺(tái)圖片的。

class App extends Component {
  state = {
    url: ""
  }

  componentDidMount() {
    this.setState({ url: getImage() })
  }

  onReload = () => {
    this.setState({ url: getImage() })
  }
  render() {
    return (
      <div>
        <ImageCode
          imageUrl={this.state.url}
          onReload={this.onReload}
          onMatch={() => {
            console.log("code is match")
          }}
        />
      </div>
    )
  }
}

上代碼

// index.js
/**
 * @name ImageCode
 * @desc 滑動(dòng)拼圖驗(yàn)證
 * @author darcrand
 * @version 2019-02-26
 *
 * @param {String} imageUrl 圖片的路徑
 * @param {Number} imageWidth 展示圖片的寬帶
 * @param {Number} imageHeight 展示圖片的高帶
 * @param {Number} fragmentSize 滑動(dòng)圖片的尺寸
 * @param {Function} onReload 當(dāng)點(diǎn)擊'重新驗(yàn)證'時(shí)執(zhí)行的函數(shù)
 * @param {Function} onMath 匹配成功時(shí)執(zhí)行的函數(shù)
 * @param {Function} onError 匹配失敗時(shí)執(zhí)行的函數(shù)
 */

import React from "react"

import "./styles.css"

const icoSuccess = require("./icons/success.png")
const icoError = require("./icons/error.png")
const icoReload = require("./icons/reload.png")
const icoSlider = require("./icons/slider.png")

const STATUS_LOADING = 0 // 還沒有圖片
const STATUS_READY = 1 // 圖片渲染完成,可以開始滑動(dòng)
const STATUS_MATCH = 2 // 圖片位置匹配成功
const STATUS_ERROR = 3 // 圖片位置匹配失敗

const arrTips = [{ ico: icoSuccess, text: "匹配成功" }, { ico: icoError, text: "匹配失敗" }]

// 生成裁剪路徑
function createClipPath(ctx, size = 100, styleIndex = 0) {
  const styles = [
    [0, 0, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0],
    [0, 0, 1, 1],
    [0, 1, 0, 0],
    [0, 1, 0, 1],
    [0, 1, 1, 0],
    [0, 1, 1, 1],
    [1, 0, 0, 0],
    [1, 0, 0, 1],
    [1, 0, 1, 0],
    [1, 0, 1, 1],
    [1, 1, 0, 0],
    [1, 1, 0, 1],
    [1, 1, 1, 0],
    [1, 1, 1, 1]
  ]
  const style = styles[styleIndex]

  const r = 0.1 * size
  ctx.save()
  ctx.beginPath()
  // left
  ctx.moveTo(r, r)
  ctx.lineTo(r, 0.5 * size - r)
  ctx.arc(r, 0.5 * size, r, 1.5 * Math.PI, 0.5 * Math.PI, style[0])
  ctx.lineTo(r, size - r)
  // bottom
  ctx.lineTo(0.5 * size - r, size - r)
  ctx.arc(0.5 * size, size - r, r, Math.PI, 0, style[1])
  ctx.lineTo(size - r, size - r)
  // right
  ctx.lineTo(size - r, 0.5 * size + r)
  ctx.arc(size - r, 0.5 * size, r, 0.5 * Math.PI, 1.5 * Math.PI, style[2])
  ctx.lineTo(size - r, r)
  // top
  ctx.lineTo(0.5 * size + r, r)
  ctx.arc(0.5 * size, r, r, 0, Math.PI, style[3])
  ctx.lineTo(r, r)

  ctx.clip()
  ctx.closePath()
}

class ImageCode extends React.Component {
  static defaultProps = {
    imageUrl: "",
    imageWidth: 500,
    imageHeight: 300,
    fragmentSize: 80,
    onReload: () => {},
    onMatch: () => {},
    onError: () => {}
  }

  state = {
    isMovable: false,
    offsetX: 0, //圖片截取的x
    offsetY: 0, //圖片截取的y
    startX: 0, // 開始滑動(dòng)的 x
    oldX: 0,
    currX: 0, // 滑塊當(dāng)前 x,
    status: STATUS_LOADING,
    showTips: false,
    tipsIndex: 0
  }

  componentDidUpdate(prevProps) {
    // 當(dāng)父組件傳入新的圖片后,開始渲染
    if (!!this.props.imageUrl && prevProps.imageUrl !== this.props.imageUrl) {
      this.renderImage()
    }
  }

  renderImage = () => {
    // 初始化狀態(tài)
    this.setState({ status: STATUS_LOADING })

    // 創(chuàng)建一個(gè)圖片對(duì)象,主要用于canvas.context.drawImage()
    const objImage = new Image()

    objImage.addEventListener("load", () => {
      const { imageWidth, imageHeight, fragmentSize } = this.props

      // 先獲取兩個(gè)ctx
      const ctxShadow = this.refs.shadowCanvas.getContext("2d")
      const ctxFragment = this.refs.fragmentCanvas.getContext("2d")

      // 讓兩個(gè)ctx擁有同樣的裁剪路徑(可滑動(dòng)小塊的輪廓)
      const styleIndex = Math.floor(Math.random() * 16)
      createClipPath(ctxShadow, fragmentSize, styleIndex)
      createClipPath(ctxFragment, fragmentSize, styleIndex)

      // 隨機(jī)生成裁剪圖片的開始坐標(biāo)
      const clipX = Math.floor(fragmentSize + (imageWidth - 2 * fragmentSize) * Math.random())
      const clipY = Math.floor((imageHeight - fragmentSize) * Math.random())

      // 讓小塊繪制出被裁剪的部分
      ctxFragment.drawImage(objImage, clipX, clipY, fragmentSize, fragmentSize, 0, 0, fragmentSize, fragmentSize)

      // 讓陰影canvas帶上陰影效果
      ctxShadow.fillStyle = "rgba(0, 0, 0, 0.5)"
      ctxShadow.fill()

      // 恢復(fù)畫布狀態(tài)
      ctxShadow.restore()
      ctxFragment.restore()

      // 設(shè)置裁剪小塊的位置
      this.setState({ offsetX: clipX, offsetY: clipY })

      // 修改狀態(tài)
      this.setState({ status: STATUS_READY })
    })

    objImage.src = this.props.imageUrl
  }

  onMoveStart = e => {
    if (this.state.status !== STATUS_READY) {
      return
    }

    // 記錄滑動(dòng)開始時(shí)的絕對(duì)坐標(biāo)x
    this.setState({ isMovable: true, startX: e.clientX })
  }

  onMoving = e => {
    if (this.state.status !== STATUS_READY || !this.state.isMovable) {
      return
    }
    const distance = e.clientX - this.state.startX
    let currX = this.state.oldX + distance

    const minX = 0
    const maxX = this.props.imageWidth - this.props.fragmentSize
    currX = currX < minX ? 0 : currX > maxX ? maxX : currX

    this.setState({ currX })
  }

  onMoveEnd = () => {
    if (this.state.status !== STATUS_READY || !this.state.isMovable) {
      return
    }
    // 將舊的固定坐標(biāo)x更新
    this.setState(pre => ({ isMovable: false, oldX: pre.currX }))

    const isMatch = Math.abs(this.state.currX - this.state.offsetX) < 5
    if (isMatch) {
      this.setState(pre => ({ status: STATUS_MATCH, currX: pre.offsetX }), this.onShowTips)
      this.props.onMatch()
    } else {
      this.setState({ status: STATUS_ERROR }, () => {
        this.onReset()
        this.onShowTips()
      })
      this.props.onError()
    }
  }

  onReset = () => {
    const timer = setTimeout(() => {
      this.setState({ oldX: 0, currX: 0, status: STATUS_READY })
      clearTimeout(timer)
    }, 1000)
  }

  onReload = () => {
    if (this.state.status !== STATUS_READY && this.state.status !== STATUS_MATCH) {
      return
    }
    const ctxShadow = this.refs.shadowCanvas.getContext("2d")
    const ctxFragment = this.refs.fragmentCanvas.getContext("2d")

    // 清空畫布
    ctxShadow.clearRect(0, 0, this.props.fragmentSize, this.props.fragmentSize)
    ctxFragment.clearRect(0, 0, this.props.fragmentSize, this.props.fragmentSize)

    this.setState(
      {
        isMovable: false,
        offsetX: 0, //圖片截取的x
        offsetY: 0, //圖片截取的y
        startX: 0, // 開始滑動(dòng)的 x
        oldX: 0,
        currX: 0, // 滑塊當(dāng)前 x,
        status: STATUS_LOADING
      },
      this.props.onReload
    )
  }

  onShowTips = () => {
    if (this.state.showTips) {
      return
    }

    const tipsIndex = this.state.status === STATUS_MATCH ? 0 : 1
    this.setState({ showTips: true, tipsIndex })
    const timer = setTimeout(() => {
      this.setState({ showTips: false })
      clearTimeout(timer)
    }, 2000)
  }

  render() {
    const { imageUrl, imageWidth, imageHeight, fragmentSize } = this.props
    const { offsetX, offsetY, currX, showTips, tipsIndex } = this.state
    const tips = arrTips[tipsIndex]

    return (
      <div className="image-code" style={{ width: imageWidth }}>
        <div className="image-container" style={{ height: imageHeight, backgroundImage: `url("${imageUrl}")` }}>
          <canvas
            ref="shadowCanvas"
            className="canvas"
            width={fragmentSize}
            height={fragmentSize}
            style={{ left: offsetX + "px", top: offsetY + "px" }}
          />
          <canvas
            ref="fragmentCanvas"
            className="canvas"
            width={fragmentSize}
            height={fragmentSize}
            style={{ top: offsetY + "px", left: currX + "px" }}
          />

          <div className={showTips ? "tips-container--active" : "tips-container"}>
            <i className="tips-ico" style={{ backgroundImage: `url("${tips.ico}")` }} />
            <span className="tips-text">{tips.text}</span>
          </div>
        </div>

        <div className="reload-container">
          <div className="reload-wrapper" onClick={this.onReload}>
            <i className="reload-ico" style={{ backgroundImage: `url("${icoReload}")` }} />
            <span className="reload-tips">刷新驗(yàn)證</span>
          </div>
        </div>

        <div className="slider-wrpper" onMouseMove={this.onMoving} onMouseLeave={this.onMoveEnd}>
          <div className="slider-bar">按住滑塊,拖動(dòng)完成拼圖</div>
          <div
            className="slider-button"
            onMouseDown={this.onMoveStart}
            onMouseUp={this.onMoveEnd}
            style={{ left: currX + "px", backgroundImage: `url("${icoSlider}")` }}
          />
        </div>
      </div>
    )
  }
}

export default ImageCode
// styles.css

.image-code {
  padding: 10px;
  user-select: none;
}

.image-container {
  position: relative;
  background-color: #ddd;
}

.canvas {
  position: absolute;
  top: 0;
  left: 0;
}

.reload-container {
  margin: 20px 0;
}

.reload-wrapper {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
}

.reload-ico {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  background: center/cover no-repeat;
}

.reload-tips {
  font-size: 14px;
  color: #666;
}

.slider-wrpper {
  position: relative;
  margin: 10px 0;
}

.slider-bar {
  padding: 10px;
  font-size: 14px;
  text-align: center;
  color: #999;
  background-color: #ddd;
}

.slider-button {
  position: absolute;
  top: 50%;
  left: 0;
  width: 50px;
  height: 50px;
  border-radius: 25px;
  transform: translateY(-50%);
  cursor: pointer;
  background: #fff center/80% 80% no-repeat;
  box-shadow: 0 2px 10px 0 #333;
}

/* 提示信息 */
.tips-container,
.tips-container--active {
  position: absolute;
  top: 50%;
  left: 50%;
  display: flex;
  align-items: center;
  padding: 10px;
  transform: translate(-50%, -50%);
  transition: all 0.25s;
  background: #fff;
  border-radius: 5px;

  visibility: hidden;
  opacity: 0;
}

.tips-container--active {
  visibility: visible;
  opacity: 1;
}

.tips-ico {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  background: center/cover no-repeat;
}

.tips-text {
  color: #666;
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • React進(jìn)階學(xué)習(xí)之組件的解耦之道

    React進(jìn)階學(xué)習(xí)之組件的解耦之道

    這篇文章主要給大家介紹了關(guān)于React進(jìn)階之組件的解耦之道,文中通過詳細(xì)的示例代碼給大家介紹了組件分割與解耦的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-08-08
  • React Native功能豐富的Toast通知庫

    React Native功能豐富的Toast通知庫

    這篇文章主要為大家介紹了React Native功能豐富的Toast通知庫使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • React實(shí)現(xiàn)雙向綁定示例代碼

    React實(shí)現(xiàn)雙向綁定示例代碼

    這篇文章給大家介紹了在React中如何實(shí)現(xiàn)雙向綁定,文中給出了示例代碼,對(duì)大家的理解與學(xué)習(xí)很有幫助,有需要的朋友下面來一起看看吧。
    2016-09-09
  • React?useEffect異步操作常見問題小結(jié)

    React?useEffect異步操作常見問題小結(jié)

    本文主要介紹了React?useEffect異步操作常見問題小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 30分鐘帶你全面了解React Hooks

    30分鐘帶你全面了解React Hooks

    Hooks是一種函數(shù),該函數(shù)允許您從函數(shù)式組件 “勾住(hook into)”React狀態(tài)和生命周期功能。Hooks在類內(nèi)部不起作用 - 它們?cè)试S你無需類就使用 React。
    2021-05-05
  • 關(guān)于React16.0的componentDidCatch方法解讀

    關(guān)于React16.0的componentDidCatch方法解讀

    這篇文章主要介紹了關(guān)于React16.0的componentDidCatch方法解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 基于react封裝一個(gè)通用可編輯組件

    基于react封裝一個(gè)通用可編輯組件

    前段時(shí)間接到這樣一個(gè)需求,需要封裝一個(gè)組件實(shí)現(xiàn)可編輯,這個(gè)到底有多通用呢,就是需要在普通的文字展示包括表格,列表等等,所以本文將給大家介紹如何基于react封裝一個(gè)通用可編輯組件,需要的朋友可以參考下
    2024-02-02
  • React中組件優(yōu)化的最佳方案分享

    React中組件優(yōu)化的最佳方案分享

    React組件性能優(yōu)化可以減少渲染真實(shí)DOM的頻率,以及減少VD比對(duì)的頻率,本文為大家整理了一些有效的React組件優(yōu)化方法,需要的小伙伴可以參考下
    2023-12-12
  • 使用useMutation和React Query發(fā)布數(shù)據(jù)demo

    使用useMutation和React Query發(fā)布數(shù)據(jù)demo

    這篇文章主要為大家介紹了使用useMutation和React Query發(fā)布數(shù)據(jù)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • React?Context源碼實(shí)現(xiàn)原理詳解

    React?Context源碼實(shí)現(xiàn)原理詳解

    這篇文章主要為大家介紹了React?Context源碼實(shí)現(xiàn)原理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10

最新評(píng)論