【无标题】

前端验证码如何制作

本质上就是canvas,倘若你还不会canvas,那么就去MDN搜一下,学一学2d下的API,就能使用了

直接上代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas class="canvas" width="200" height="60"></canvas>
  <script>
    const drawing = document.querySelector('.canvas')
    const context = drawing.getContext("2d")

    init([1, 2, 3, 4])
    drawing.addEventListener('click', () => {
      let arr = []
      for (let i = 0; i < 4; i++) {
        arr.push(Math.floor(Math.random() * 10))
      }
      console.log(arr)
      init(arr)
    })
    function init(arr) {
      // // 填充颜色
      context.fillStyle = "lightblue"
      // // 绘制一个填充的矩形
      context.fillRect(0, 0, 500, 500)
      // // 绘制一个描边的矩形
      // context.strokeRect(30, 30, 50, 50)

      context.strokeStyle = 'black'
      context.strokeRect(0, 0, 200, 60)
      drawLine(context)
      drawPoint(context)
      drawCharacter(context, arr)
    }

    // 绘制干扰线
    function drawLine(ctx) {
      for (let i = 1; i <= 10; i++) {
        let x = Math.round(Math.random() * 255)
        let y = Math.round(Math.random() * 255)
        let z = Math.round(Math.random() * 255)
        ctx.fillStyle = `rgb(${x},${y},${z})`
        ctx.beginPath()
        let y1 = Math.round(Math.random() * 40)
        let x1 = Math.round(Math.random() * 200)
        let y2 = Math.round(Math.random() * 40)
        let x2 = Math.round(Math.random() * 200)
        ctx.moveTo(x1, y1)
        ctx.lineTo(x2, y2)
        ctx.fill()
      }
    }
    // 绘制圆点
    function drawPoint(ctx) {
      for (let i = 1; i <= 100; i++) {
        let x = Math.round(Math.random() * 255)
        let y = Math.round(Math.random() * 255)
        let z = Math.round(Math.random() * 255)
        ctx.fillStyle = `rgb(${x},${y},${z})`
        ctx.beginPath()
        let y1 = Math.round(Math.random() * 40)
        let x1 = Math.round(Math.random() * 200)
        ctx.arc(x1, y1, 1, 0, 2 * Math.PI, false)
        ctx.fill()
      }
    }
    // 绘制字体
    function drawCharacter(ctx, fonts) {
      let i = 0
      for (let i = 0; i < fonts.length; i++) {
        let x = Math.round(Math.random() * 255)
        let y = Math.round(Math.random() * 255)
        let z = Math.round(Math.random() * 255)
        ctx.fillStyle = `rgb(${x},${y},${z})`
        ctx.font = 'bold 45px Arial'
        ctx.textBaseline = 'baseline'
        ctx.fillText(fonts[i], 50 + i * 30, 40)
      }
    }
  </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值