DEV Community

Manzoor Samejo
Manzoor Samejo

Posted on

Why HTML5 Canvas Downloads a Blank Image (and How to Fix It)

I have a WordPress website ([ambigramtools.com]) where I generate ambigram text using HTML5 canvas and JavaScript.

The ambigram is displayed correctly on the screen after generation, but when I try to download the canvas as an image, the downloaded file is completely white/blank. The generated ambigram text is not included in the downloaded canvas.

What works

  • Ambigram text is visible on screen
  • Canvas element exists and shows correct size
  • Download function is triggered correctly

What does NOT work

  • "canvas.toDataURL()" returns a blank white image
  • Text drawn on canvas does not appear in the downloaded image

Possible causes I suspect

  • Web fonts not fully loaded before drawing text
  • Canvas content is drawn via CSS transforms (rotate / scale)
  • Drawing happens on a different canvas than the one being downloaded
  • Canvas width/height mismatch

Simplified code

const canvas = document.getElementById("ambigramCanvas");
const ctx = canvas.getContext("2d");

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "40px AmbigramFont";
ctx.textAlign = "center";
ctx.fillStyle = "#000";
ctx.fillText("TEST", canvas.width / 2, canvas.height / 2);

function downloadCanvas() {
const link = document.createElement("a");
link.download = "ambigram.png";
link.href = canvas.toDataURL("image/png");
link.click();
}

Question

What is the correct way to ensure that:

  • The generated ambigram text is actually drawn into the canvas
  • Web fonts are fully loaded before exporting
  • The downloaded canvas image matches what is visually displayed?

Any guidance or best practice would be appreciated.

Top comments (0)