Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"You need to specify a canvas element" error when using Cloudflare Workers with qrcode #349

Open
bkyerv opened this issue Sep 15, 2023 · 5 comments

Comments

@bkyerv
Copy link

bkyerv commented Sep 15, 2023

I am encountering an error when attempting to generate a QR code using the qrcode library within a Cloudflare Worker. The error message is "You need to specify a canvas element".

Error stack:

Error: You need to specify a canvas element
    at getCanvasElement (index.js:2058:15)
    at Object.render (index.js:2069:20)
    at renderToDataURL (index.js:2088:32)
    at renderCanvas (index.js:2214:18)
    at qr (index.js:2307:31)
    at new Promise (<anonymous>)
    at Object.fetch (index.js:2306:24)
    at async jsonError (index.js:2337:12) {
  stack: Error: You need to specify a canvas element
    at…306:24)
    at async jsonError (index.js:2337:12),
  message: You need to specify a canvas element
}

Environment:

Using Cloudflare Workers.
Implementing the server API of the qrcode library.

Steps to Reproduce:

Set up a Cloudflare Worker.
Integrate the qrcode library to generate a QR code.
Execute the worker function to generate the QR code.

Expected Result:
The QR code should be generated successfully.

Actual Result:
Encountering the above error, which seems to suggest a canvas element is required.

I would appreciate any guidance or suggestions on how to resolve this issue, especially considering the context of using Cloudflare Workers where a DOM-based canvas isn't available.

Thank you!

Below is the source code for the worker

export default {
	async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
		
		if (request.method !== 'POST') {
			return new Response('Method not allowed', { status: 405 });
		}

		try {
			const payload = await request.json();
			
			const qr = await QRCode.toDataURL(payload.uniqueTitle, { type: 'image/webp' });
			
                        return new Response(qr);

		} catch (e) {
			console.error(e);
			return new Response(null, { status: 500});
		}
	},
};

@lexakozakov
Copy link

same here

@kamil-homernik
Copy link

I'm also looking for a solution to generate QR codes without access to DOM

@feri-irawan
Copy link

Try using node-canvas

@evanoxu
Copy link

evanoxu commented Mar 26, 2024

same here

@techieshark
Copy link

Not a fix for this library, but if anyone is desperate here might be some leads

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants