Javascript Add Text To Image (Simple Examples)

Welcome to a tutorial on how to add text to images in Javascript. Yes, you read that right. Modern Javascript is fully capable of processing images, there’s no need to upload the images to the server. Let us walk through a few examples in this guide – Read on!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/add-text-to-image-javascript/” title=”Add Text To Image In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT ADD TEXT TO IMAGE

All right, let us now get into the examples of adding text to an image in Javascript.

 

1) SIMPLE “WRITE TEXT TO IMAGE”

1-simple-text.html
<!-- (A) EMPTY CANVAS -->
<canvas id="demo"></canvas>
 
<script>
// (B) IMAGE + TEXT + CANVAS
var img = new Image(),
    txt = "PIZZA!",
    canvas = document.getElementById("demo"),
    ctx = canvas.getContext("2d");
 
// (C) WRITE TEXT ON IMAGE
img.onload = () => {
  // (C1) SOURCE IMAGE
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
 
  // (C2) ADD TEXT
  ctx.font = "bold 50px Arial";
  ctx.fillStyle = "rgb(255, 255, 255)";
  ctx.fillText(txt, 0, 50);
};
 
// (D) GO!
img.src = "demo.png";
</script>

  • (A & B) The magic to “write text on image” is actually a canvas and image object.
  • (D) Set the image to which we want to add text to.
  • (C) When the image is fully loaded:
    • (C1) We draw the image onto the canvas.
    • (C2) Then, add the text onto the canvas.

Yep, that pretty much wraps up the basic mechanics of “add text to image”.

 

 

2) MORE TEXT OPTIONS & “FORCE DOWNLOAD”

2-more-text.html
// (A) IMAGE + TEXT + CANVAS
var img = new Image(),
    txt = "PIZZA!",
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");
 
// (B) WRITE TEXT ON IMAGE
img.onload = () => {
  // (B1) SOURCE IMAGE
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
 
  // (B2) ADD TEXT
  ctx.font = "bold 50px Arial";
  ctx.strokeStyle = "black";
  ctx.lineWidth = 2;
  ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
  ctx.strokeText(txt, 0, 50);
  ctx.fillText(txt, 0, 50);
 
  // (B3) "FORCE DOWNLOAD"
  let anchor = document.createElement("a");
  anchor.href = canvas.toDataURL("image/webp");
  anchor.download = "download.webp";
  anchor.click();
  anchor.remove();
};
 
// (C) GO!
img.src = "demo.png";

  • (A) Take note, we are creating canvas = document.createElement("canvas") and not appending it to the document. This will become an “invisible canvas”, good for you guys who don’t want to show the image on the page itself.
  • (B1 & B2) “Draw the image onto canvas” remains the same. But take note, we can stroke (outline) the text, even set it to be transparent.
  • (B3) To “force download” the complete image, we can create an <a> link and click on it. Bad news though, this may not always work depending on the user’s security settings. You may want to add the download link on the page and let the user manually click on it.

 

 

3) CENTER TEXT ON IMAGE

3-center-text.html
<!-- (A) EMPTY CANVAS -->
<canvas id="demo"></canvas>
 
<script>
// (B) IMAGE + TEXT + CANVAS
var img = new Image(),
    txt = "PIZZA!",
    canvas = document.getElementById("demo"),
    ctx = canvas.getContext("2d");
 
// (C) WRITE TEXT ON IMAGE
img.onload = () => {
  // (C1) SOURCE IMAGE
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
 
  // (C2) TEXT DIMENSIONS
  ctx.font = "bold 50px Arial";
  ctx.strokeStyle = "black";
  ctx.lineWidth = 5;
  ctx.fillStyle = "rgb(255, 255, 255)";
  let td = ctx.measureText(txt),
      tw = td.width,
      th = td.actualBoundingBoxAscent + td.actualBoundingBoxDescent;
  console.log(tw); // text box width
  console.log(th); // text box height
 
  // (C3) CALCULATE & WRITE ON CENTER
  let x = Math.floor((img.naturalWidth - tw) / 2),
      y = Math.floor((img.naturalHeight - th) / 2);
  ctx.strokeText(txt, x, y);
  ctx.fillText(txt, x, y);
};
 
// (D) GO!
img.src = "demo.png";
</script>

Centering the text is sadly Mathematical.

  • (C1) Getting the dimensions of the image is not a problem at all.
  • (C2) To calculate the dimensions of the text, we can use measureText().
  • (C3) Lastly, calculate the center “XY” position to write the text on. In “plain English”:
    • X = FLOOR((IMAGE WIDTH - TEXT WIDTH) ÷ 2)
    • Y = FLOOR((IMAGE HEIGHT - TEXT HEIGHT) ÷ 2)

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

The above examples will work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Add Text To Image (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *