1

我知道这个问题已经被问过了,但我的情况没有单一的解决方案。我正在使用三个字母的 JavaScript 生成验证码,并且能够将它们转换为 base64 字符串,以便能够进一步将其转换为图像文件并显示在浏览器上。我无法将 base64 格式转换为图像格式。我可以使用 Google reCaptcha,但我这样做是为了学习。所以任何帮助都会很棒!这是我的 JavaScript 代码:

var code2 = ''
$('#captCha').ready(function Captcha() {
    var alpha = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')

    for (var i = 0; i < 6; i++) {
        var a = alpha[Math.floor(Math.random() * alpha.length)]
        var b = alpha[Math.floor(Math.random() * alpha.length)]
        var c = alpha[Math.floor(Math.random() * alpha.length)]
    }
    var code = a + ' ' + b + ' ' + ' ' + c

    code2 = removeSpaces(code)
    var b64 = btoa(unescape(encodeURIComponent(code2)))
    console.log(b64)
    document.getElementById('captCha').innerHTML = b64
});

function removeSpaces (string) {
    return string.split(' ').join('')
}
4

1 回答 1

1

您可以在元素上绘制文本canvas,然后从画布中获取 base64 编码的图像:

const alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
               'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 
               'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
               'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

const a = alpha[Math.floor(Math.random() * alpha.length)];
const b = alpha[Math.floor(Math.random() * alpha.length)];
const c = alpha[Math.floor(Math.random() * alpha.length)];
const code = a + ' ' + b + ' ' + c;

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = '24px sans-serif';
context.fillText(code, 10, 50);

const img = document.createElement('img');
img.setAttribute('src', canvas.toDataURL());

document.body.appendChild(img);

于 2018-01-05T08:50:53.053 回答