• Convert HTMLCanvasElement to Blob.

    Exports the canvas content as a binary blob in the specified format. Defaults to PNG format if no mime type is provided.

    Parameters

    • canvas: HTMLCanvasElement

      The canvas to convert

    • mimeType: string = 'image/png'

      The MIME type for the output blob (default: 'image/png')

    Returns Promise<Blob>

    Promise that resolves to a Blob containing the image data

    Throws

    When canvas conversion fails

    Example

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.fillRect(0, 0, 100, 100);

    // Convert to PNG blob
    const pngBlob = await canvasToBlob(canvas);

    // Convert to JPEG blob
    const jpegBlob = await canvasToBlob(canvas, 'image/jpeg');

    // Download the blob
    const url = URL.createObjectURL(pngBlob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'image.png';
    a.click();