canvas 实现简单验证码

canvas 实现简单验证码




  
  
  JS Bin


a canvas
  * {
      box-sizing: border-box;
      margin: 0;
    }

    #CANVAS {
      box-shadow: 0 0 0 1px tomato;
      padding: 0px;
      transform: scale(0.5);
      transform-origin: top left;
      cursor: pointer;
    }

    .canvas-wrapper {
      margin-left: 20px;
      margin-top: 20px;
    }
const numberStore = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
let numberRenderArr = [];
const numberAttributeArr = [{
          color: '#C32D62'
        }, {
          color: '#ffc107'
        }, {
          color: '#FFEB3B'
        }, {
          color: '#4caf50'  
        }, {
          color: '#cddc39'  
        }, {
          color: '#3f51b5'  
        }, {
          color: '#673ab7'  
        }];
const context = CANVAS.getContext("2d");

function generateOriginData() {
  numberRenderArr = [];
  for(let i = 0; i < numberAttributeArr.length; i++) {
    numberRenderArr.push(numberStore[parseInt(Math.random() * numberStore.length)])
  }
}

function renderData() {
  context.beginPath();
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.font = "bold 100px monaco";
  
  const gap = CANVAS.width / 2 / numberAttributeArr.length;

  numberRenderArr.forEach((v, i) => {
    context.save();
    context.fillStyle = numberAttributeArr[i].color;  // 填充颜色为红色
    // 192 / 2 / 4 = 24
    context.translate(gap * (2 * i + 1), CANVAS.height / 2);
    context.rotate((Math.random() - 0.5) * 45 * Math.PI / 180);
    context.fillText(v, 0, 0);
    context.restore();
  });
  context.closePath();
  renderSalt();
}

function renderSalt() {
  context.beginPath();
  context.strokeStyle = 'rgba(180, 180, 180, 0.8)';
  context.lineWidth = 4;
  for(let i = 0; i < 100; i++) {
    const randomX = parseInt(Math.random() * CANVAS.width);
    const randomY = parseInt(Math.random() * CANVAS.height);
    context.moveTo(randomX, randomY);
    context.lineTo(randomX + ((Math.random() - 0.5) * 30), randomY + parseInt((Math.random() - 0.5) * 30));
  }
  context.stroke();
  context.closePath();
}

function resetCode() {
  console.log(context);
  generateOriginData();
  context.clearRect(0,0,CANVAS.width,CANVAS.height);
  renderData();
}

generateOriginData();
renderData();

CANVAS.addEventListener('click', function() {
  resetCode();
})

你可能感兴趣的:(canvas 实现简单验证码)