How to add text on image using javascript and canvas?

Member

by denis , in category: HTML & CSS , 6 months ago

How to add text on image using javascript and canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 6 months ago

@denis 

To add text on an image using JavaScript and Canvas, you can follow these steps:

  1. Create an HTML
1
<canvas id="myCanvas"></canvas>


  1. Get the reference to the canvas using JavaScript:
1
2
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");


  1. Load the image using JavaScript:
1
2
var image = new Image();
image.src = "path/to/image.jpg";


  1. Once the image is loaded, draw it on the canvas:
1
2
3
image.onload = function() {
  ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
};


  1. Set the font and text properties:
1
2
3
ctx.font = "30px Arial";
ctx.fillStyle = "white";
ctx.textAlign = "center";


  1. Use the fillText() method to add the text on the canvas:
1
ctx.fillText("Sample Text", canvas.width/2, canvas.height/2);


Here, "Sample Text" is the text you want to display.

  1. Optionally, you can customize the position, style, and properties of the added text, based on your requirements.
  2. To save the canvas as an image, you can convert it to a data URL using the toDataURL() method:
1
var dataURL = canvas.toDataURL();  // returns base64-encoded image data


You can then use this dataURL to display or save the image.


By following these steps, you can add text on an image using JavaScript and the HTML5 Canvas element.