JS实现滑动拼图验证功能完整示例


Posted in Javascript onMarch 29, 2020

本文实例讲述了JS实现滑动拼图验证功能。分享给大家供大家参考,具体如下:

先看一下效果图:

JS实现滑动拼图验证功能完整示例

JS实现滑动拼图验证功能完整示例

JS实现滑动拼图验证功能完整示例

设置画布滑块属性

const l = 42, // 滑块边长
 r = 10, // 滑块半径
 w = 310, // canvas宽度
 h = 155, // canvas高度
 PI = Math.PI
const L = l + r * 2 // 滑块实际边长

设置背景图片:

图片链接地址可以自行更换

function getRandomImg() {
 return 'https://picsum.photos/300/150/?image=' + getRandomNumberByRange(0, 100)
}

CSS部分代码:

.container {
 width: 310px;
 margin: 100px auto;
}
#msg {
 width: 100%;
 line-height: 40px;
 font-size: 14px;
 text-align: center;
}
a:link,
a:visited,
a:hover,
a:active {
 margin-left: 100px;
 color: #0366D6;
}
.block {
 position: absolute;
 left: 0;
 top: 0;
}
.sliderContainer {
 position: relative;
 text-align: center;
 width: 310px;
 height: 40px;
 line-height: 40px;
 margin-top: 15px;
 background: #f7f9fa;
 color: #45494c;
 border: 1px solid #e4e7eb;
}
.sliderContainer_active .slider {
 height: 38px;
 top: -1px;
 border: 1px solid #1991FA;
}
.sliderContainer_active .sliderMask {
 height: 38px;
 border-width: 1px;
}
.sliderContainer_success .slider {
 height: 38px;
 top: -1px;
 border: 1px solid #52CCBA;
 background-color: #52CCBA !important;
}
.sliderContainer_success .sliderMask {
 height: 38px;
 border: 1px solid #52CCBA;
 background-color: #D2F4EF;
}
.sliderContainer_success .sliderIcon {
 background-position: 0 0 !important;
}
.sliderContainer_fail .slider {
 height: 38px;
 top: -1px;
 border: 1px solid #f57a7a;
 background-color: #f57a7a !important;
}
.sliderContainer_fail .sliderMask {
 height: 38px;
 border: 1px solid #f57a7a;
 background-color: #fce1e1;
}
.sliderContainer_fail .sliderIcon {
 background-position: 0 -83px !important;
}
.sliderContainer_active .sliderText,
.sliderContainer_success .sliderText,
.sliderContainer_fail .sliderText {
 display: none;
}
.sliderMask {
 position: absolute;
 left: 0;
 top: 0;
 height: 40px;
 border: 0 solid #1991FA;
 background: #D1E9FE;
}
.slider {
 position: absolute;
 top: 0;
 left: 0;
 width: 40px;
 height: 40px;
 background: #fff;
 box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
 cursor: pointer;
 transition: background .2s linear;
}
.slider:hover {
 background: #1991FA;
}
.slider:hover .sliderIcon {
 background-position: 0 -13px;
}
.sliderIcon {
 position: absolute;
 top: 15px;
 left: 13px;
 width: 14px;
 height: 10px;
 background: url(img/tb.png) 0 -26px;
 background-size: 34px 471px;
}
.refreshIcon {
 position: absolute;
 right: 0;
 top: 0;
 width: 34px;
 height: 34px;
 cursor: pointer;
 background: url(img/tb.png) 0 -437px;
 background-size: 34px 471px;
}

页面,页面只用放一个div就可以了

<div class="container">
 <div id="captcha" style="position: relative"></div>
</div>

js部分代码,包括验证是否正确

<script type="text/javascript">
 (function(window) {
 const l = 42, // 滑块边长
  r = 10, // 滑块半径
  w = 310, // canvas宽度
  h = 155, // canvas高度
  PI = Math.PI
 const L = l + r * 2 // 滑块实际边长
 function getRandomNumberByRange(start, end) {
  return Math.round(Math.random() * (end - start) + start)
 }
 function createCanvas(width, height) {
  const canvas = createElement('canvas')
  canvas.width = width
  canvas.height = height
  return canvas
 }
 function createImg(onload) {
  const img = createElement('img')
  img.crossOrigin = "Anonymous"
  img.onload = onload
  img.onerror = () => {
  img.src = getRandomImg()
  }
  img.src = getRandomImg()
  return img
 }
 function createElement(tagName) {
  return document.createElement(tagName)
 }
 function addClass(tag, className) {
  tag.classList.add(className)
 }
 function removeClass(tag, className) {
  tag.classList.remove(className)
 }
 function getRandomImg() {
  return 'https://picsum.photos/300/150/?image=' + getRandomNumberByRange(0, 100)
 }
 function draw(ctx, operation, x, y) {
  ctx.beginPath()
  ctx.moveTo(x, y)
  ctx.lineTo(x + l / 2, y)
  ctx.arc(x + l / 2, y - r + 2, r, 0, 2 * PI)
  ctx.lineTo(x + l / 2, y)
  ctx.lineTo(x + l, y)
  ctx.lineTo(x + l, y + l / 2)
  ctx.arc(x + l + r - 2, y + l / 2, r, 0, 2 * PI)
  ctx.lineTo(x + l, y + l / 2)
  ctx.lineTo(x + l, y + l)
  ctx.lineTo(x, y + l)
  ctx.lineTo(x, y)
  ctx.fillStyle = '#fff'
  ctx[operation]()
  ctx.beginPath()
  ctx.arc(x, y + l / 2, r, 1.5 * PI, 0.5 * PI)
  ctx.globalCompositeOperation = "xor"
  ctx.fill()
 }
 function sum(x, y) {
  return x + y
 }
 function square(x) {
  return x * x
 }
 class jigsaw {
  constructor(el, success, fail) {
  this.el = el
  this.success = success
  this.fail = fail
  }
  init() {
  this.initDOM()
  this.initImg()
  this.draw()
  this.bindEvents()
  }
  initDOM() {
  const canvas = createCanvas(w, h) // 画布
  const block = canvas.cloneNode(true) // 滑块
  const sliderContainer = createElement('div')
  const refreshIcon = createElement('div')
  const sliderMask = createElement('div')
  const slider = createElement('div')
  const sliderIcon = createElement('span')
  const text = createElement('span')
  block.className = 'block'
  sliderContainer.className = 'sliderContainer'
  refreshIcon.className = 'refreshIcon'
  sliderMask.className = 'sliderMask'
  slider.className = 'slider'
  sliderIcon.className = 'sliderIcon'
  text.innerHTML = '向右滑动滑块填充拼图'
  text.className = 'sliderText'
  const el = this.el
  el.appendChild(canvas)
  el.appendChild(refreshIcon)
  el.appendChild(block)
  slider.appendChild(sliderIcon)
  sliderMask.appendChild(slider)
  sliderContainer.appendChild(sliderMask)
  sliderContainer.appendChild(text)
  el.appendChild(sliderContainer)
  Object.assign(this, {
   canvas,
   block,
   sliderContainer,
   refreshIcon,
   slider,
   sliderMask,
   sliderIcon,
   text,
   canvasCtx: canvas.getContext('2d'),
   blockCtx: block.getContext('2d')
  })
  }
  initImg() {
  const img = createImg(() => {
   this.canvasCtx.drawImage(img, 0, 0, w, h)
   this.blockCtx.drawImage(img, 0, 0, w, h)
   const y = this.y - r * 2 + 2
   const ImageData = this.blockCtx.getImageData(this.x, y, L, L)
   this.block.width = L
   this.blockCtx.putImageData(ImageData, 0, y)
  })
  this.img = img
  }
  draw() {
  // 随机创建滑块的位置
  this.x = getRandomNumberByRange(L + 10, w - (L + 10))
  this.y = getRandomNumberByRange(10 + r * 2, h - (L + 10))
  draw(this.canvasCtx, 'fill', this.x, this.y)
  draw(this.blockCtx, 'clip', this.x, this.y)
  }
  clean() {
  this.canvasCtx.clearRect(0, 0, w, h)
  this.blockCtx.clearRect(0, 0, w, h)
  this.block.width = w
  }
  bindEvents() {
  this.el.onselectstart = () => false
  this.refreshIcon.onclick = () => {
   this.reset()
  }
  let originX, originY, trail = [],
   isMouseDown = false
  this.slider.addEventListener('mousedown', function(e) {
   originX = e.x, originY = e.y
   isMouseDown = true
  })
  document.addEventListener('mousemove', (e) => {
   if(!isMouseDown) return false
   const moveX = e.x - originX
   const moveY = e.y - originY
   if(moveX < 0 || moveX + 38 >= w) return false
   this.slider.style.left = moveX + 'px'
   var blockLeft = (w - 40 - 20) / (w - 40) * moveX
   this.block.style.left = blockLeft + 'px'
   addClass(this.sliderContainer, 'sliderContainer_active')
   this.sliderMask.style.width = moveX + 'px'
   trail.push(moveY)
  })
  document.addEventListener('mouseup', (e) => {
   if(!isMouseDown) return false
   isMouseDown = false
   if(e.x == originX) return false
   removeClass(this.sliderContainer, 'sliderContainer_active')
   this.trail = trail
   const {
   spliced,
   TuringTest
   } = this.verify()
   if(spliced) {
   if(TuringTest) {
    addClass(this.sliderContainer, 'sliderContainer_success')
    this.success && this.success()
   } else {
    addClass(this.sliderContainer, 'sliderContainer_fail')
    this.text.innerHTML = '再试一次'
    this.reset()
   }
   } else {
   alert("验证失败");
   addClass(this.sliderContainer, 'sliderContainer_fail')
   this.fail && this.fail();
                        //验证失败后,1秒后重新加载图片
   setTimeout(() => {
    this.reset()
   }, 1000)
   }
  })
  }
  verify() {
  const arr = this.trail // 拖动时y轴的移动距离
  const average = arr.reduce(sum) / arr.length // 平均值
  const deviations = arr.map(x => x - average) // 偏差数组
  const stddev = Math.sqrt(deviations.map(square).reduce(sum) / arr.length) // 标准差
  const left = parseInt(this.block.style.left)
  return {
   spliced: Math.abs(left - this.x) < 10,
   TuringTest: average !== stddev, // 只是简单的验证拖动轨迹,相等时一般为0,表示可能非人为操作
  }
  }
  reset() {
  this.sliderContainer.className = 'sliderContainer'
  this.slider.style.left = 0
  this.block.style.left = 0
  this.sliderMask.style.width = 0
  this.clean()
  this.img.src = getRandomImg()
  this.draw()
  }
 }
 window.jigsaw = {
  init: function(element, success, fail) {
  new jigsaw(element, success, fail).init()
  }
 }
 }(window))
 jigsaw.init(document.getElementById('captcha'), function() {
 alert("验证成功");
 })
</script>

希望本文所述对大家JavaScript程序设计有所帮助。

Javascript 相关文章推荐
Javascript学习笔记之数组的遍历和 length 属性
Nov 23 Javascript
JS使用parseInt解析数字实现求和的方法
Aug 05 Javascript
JS实现的仿东京商城菜单、仿Win右键菜单及仿淘宝TAB特效合集
Sep 28 Javascript
js图片跟随鼠标移动代码
Nov 26 Javascript
JQuery ztree带筛选、异步加载实例讲解
Feb 25 Javascript
node.js实现快速截图
Aug 27 Javascript
AngularJS ngModel实现指令与输入直接的数据通信
Sep 21 Javascript
JavaScript随机生成颜色的方法
Oct 15 Javascript
用jQuery实现圆点图片轮播效果
Mar 19 Javascript
vue使用Axios做ajax请求详解
Jun 07 Javascript
Angular.js组件之input mask对input输入进行格式化详解
Jul 10 Javascript
vue中过滤器filter的讲解
Jan 21 Javascript
json_decode 索引为数字时自动排序问题解决方法
Mar 28 #Javascript
JS中FormData类实现文件上传
Mar 27 #Javascript
JS中FileReader类实现文件上传及时预览功能
Mar 27 #Javascript
js、jquery实现列表模糊搜索功能过程解析
Mar 27 #jQuery
开发Node CLI构建微信小程序脚手架的示例
Mar 27 #Javascript
微信小程序间使用navigator跳转传值问题实例分析
Mar 27 #Javascript
vue跳转页面的几种方法(推荐)
Mar 26 #Javascript
You might like
利用discuz实现PHP大文件上传应用实例代码
2008/11/14 PHP
PHP类与对象中的private访问控制的疑问
2012/11/01 PHP
php curl的深入解析
2013/06/02 PHP
PHP正则表达式入门教程(推荐)
2016/05/18 PHP
php-beanstalkd消息队列类实例分享
2017/07/19 PHP
PHP getDocNamespaces()函数讲解
2019/02/03 PHP
js解析与序列化json数据(二)序列化探讨
2013/02/01 Javascript
jquery.blockUI.js上传滚动等待效果实现思路及代码
2013/03/18 Javascript
node.js中的fs.readdir方法使用说明
2014/12/17 Javascript
jQuery中has()方法用法实例
2015/01/06 Javascript
jquery实现select选择框内容左右移动代码分享
2015/11/21 Javascript
AngularJS实现全选反选功能
2015/12/08 Javascript
JavaScript iframe数据共享接口实现方法
2016/01/06 Javascript
详谈Node.js之操作文件系统
2017/08/29 Javascript
JavaScript中如何判断一个值的类型
2017/09/15 Javascript
JS实现十字坐标跟随鼠标效果
2017/12/25 Javascript
基于vue2.0的活动倒计时组件countdown(附源码下载)
2018/10/09 Javascript
js实现延迟加载的几种方法详解
2019/01/19 Javascript
js实现页面多个日期时间倒计时效果
2019/06/20 Javascript
js实现无限瀑布流实例方法
2019/09/16 Javascript
基于vue+echarts 数据可视化大屏展示的方法示例
2020/03/09 Javascript
原生JS实现拖拽效果
2020/12/04 Javascript
Pycharm中出现ImportError:DLL load failed:找不到指定模块的解决方法
2019/09/17 Python
使用浏览器访问python写的服务器程序
2019/10/10 Python
python 追踪except信息方式
2020/04/25 Python
Pytorch转tflite方式
2020/05/25 Python
CSS3实现红包抖动效果
2020/12/23 HTML / CSS
纽约服装和生活方式品牌:Saturdays NYC
2017/08/13 全球购物
this关键字的含义
2015/04/08 面试题
什么是设计模式
2012/06/17 面试题
环境监测与治理技术专业求职信
2014/07/06 职场文书
寻找最美家庭活动方案
2014/08/20 职场文书
群众路线党员个人整改措施
2014/10/27 职场文书
幼儿园托班开学寄语(2016春季)
2015/12/03 职场文书
掌握这项技巧,一年阅读300本书不是梦
2019/09/12 职场文书
vue+element ui实现锚点定位
2021/06/29 Vue.js