node.jscanvas

TypeError: ctx.toDataURL is not a function by drawing a canvas on the node.js server side


I am creating an capacha based on canvas on the node.js server with typescript.

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()

the code is running with an error saying

TypeError: ctx.toDataURL is not a function

Solution

  • toDataURL is a function of the canvas, not of the 2d context you inferred from it. Try this:

    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()