<canvas id="captchaCanvas" width="100" height="40"></canvas>
function drawCaptcha(text) {
  const canvas = document.getElementById('captchaCanvas');
  const ctx = canvas.getContext('2d');
  // 设置背景颜色
  ctx.fillStyle = '#f0f0f0';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  // 随机生成颜色
  function randomColor() {
    return `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
  }
  // 设置字体样式
  ctx.font = '30px Arial';
  ctx.fillStyle = randomColor();
  // 在 Canvas 上绘制文本,并给每个数字一个随机的位置和旋转角度
  for (let i = 0; i < text.length; i++) {
    const x = 15 + i * 20;
    const y = 30 + Math.random() * 8 - 4;
    const angle = Math.random() * 0.3 - 0.15; // -0.15 到 0.15 弧度
    ctx.save(); // 保存当前的画布状态
    ctx.translate(x, y); // 将原点移动到字符绘制位置
    ctx.rotate(angle); // 随机旋转字符
    ctx.fillText(text[i], 0, 0); // 绘制字符
    ctx.restore(); // 恢复画布状态
  }
  // 添加一些干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = randomColor();
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }
  // 添加一些干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = randomColor();
    ctx.beginPath();
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2);
    ctx.fill();
  }
}