我正在使用 typescript 在 Node.js 服务器上创建一个基于 canvas 的 capacha。
import { createCanvas, loadImage, registerFont } from 'canvas';
const canvas = createCanvas(100, 40);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#ecedee';
ctx.fillRect(0, 0, canvas.width, canvas.height);
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();
}
ctx.font = 'bold 30px YourFontFamily';
ctx.fillStyle = '#6c757d';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(captchaText, canvas.width / 2, canvas.height / 2);
let image = ctx.toDataURL()
代码运行时出现错误提示
TypeError: ctx.toDataURL is not a function
canvas
的函数,而不是从中推断出的 2d 上下文的函数。试试这个:
import { createCanvas, loadImage, registerFont } from 'canvas';
const canvas = createCanvas(100, 40);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#ecedee';
ctx.fillRect(0, 0, canvas.width, canvas.height);
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();
}
ctx.font = 'bold 30px YourFontFamily';
ctx.fillStyle = '#6c757d';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(captchaText, canvas.width / 2, canvas.height / 2);
let image = canvas.toDataURL()