CONTENTS
Summery:
In this tutorial, we will see how to add text watermark or dynamic text on an image using jQuery.
In PHP we can insert text easily by using imagettftext. But in jQuery it is some what tricky. So lets check how to create this.
Overview:
- First, add jQuery to your project. Here I have also used Bootstrap. But it does not require for this project.
- Add a canvas element and give an id pic_canvas.
- Also, add a text input field and one button and give id to each element i.e source_text, addBtn.
- Take an image URL where you want to insert text and store it in the base_img variable.
- Load font file. I am using Google Satisfy Font.
- Write a function called startDraw() which will write text into the image.
- Call the above function whenever a user clicks on the AddText button.
Step 1: Add jQuery require elements to your project
First, we have to add jQuery to our project. I am using Bootstrap here. So copy Bootstrap boilerplate code. Also, add canvas, text input and button elements.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Add Text to Image using jquery</title>
</head>
<body>
<canvas id="pic_canvas"></canvas>
<input type="text" class="form-control" id="source_text">
<button class="btn btn-success" id="addBtn">Add Text</button>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
Step 2: Add image where the text will be shown.
We take a variable called base_img where we have store our image source.
var base_img = "https://codehasbug.com/wp-content/uploads/2021/06/good-morning.jpg";
Also we need an image object. So create an image object and two variables imgWidth and imgHeight. The two variables will store the image height and width.
Step 3: Create a blank canvas
We also need a blank canvas. Because the image and text will be written on that canvas. So select the canvas by its id “pic_canvas” that we have already added in Step 1 and store it in the canvas variable.
var canvas = document.getElementById("pic_canvas");
Step 4: Load Google font dynamically
Here we use Google font called Satisfy. But instead of linking the font at head section or by using CSS, we are going to include it by dynamically. So lets check the code first.
// load google font == Satisfy
WebFontConfig = {
google:{ families: ['Satisfy'] },
active: function(){startDraw(source_text);},
};
(function(){
var wf = document.createElement("script");
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js';
wf.async = 'true';
document.head.appendChild(wf);
})();
In the above code, you can check we have created an anonymous function. Inside it, we have created a script tag and store it in wf variable. After that, we have assigned its src attribute with https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js
.
Now here we set the async property to true and append it at the head section. In the WebFontConfig section, we have set the font family to Satisfy. But in the callback section, we called a function startDraw with a parameter source_text. In the next step, I will discuss how to create the above function.
Step 5: Create startDraw function
So lets check the code first.
function startDraw(data){
imageObj.src = base_img;
imageObj.onload = function(){
imgWidth = imageObj.width;
imgHeight = imageObj.height;
canvas.width = imgWidth;
canvas.height = imgHeight;
var context = canvas.getContext("2d");
context.clearRect(0, 0, imgWidth, imgHeight);
context.drawImage(imageObj, 0, 0, imgWidth, imgHeight);
context.font = "25px Satisfy";
context.fillStyle = "#fff";
data = data.replace(/\+/g, ' ');
context.fillText(decodeURIComponent(data), 70, 280);
};
}
In step 2, we have created an image object i.e. imageObj. Now we need to set its src property to base_img where we have stored our image path.
As its take sometime to load the image from the URL, we are going to use onload method. It means whenever the image is loaded it raise the onload event.
Now we have to assign canvas height and width with the value of image height and width. After that draw imageObj on the canvas by using drawImage.
The first time when loading the page, we don’t call startDraw() function directly. It is because we don’t know when the font will be loaded. So we call the function from the WebFontConfig section.
You can set font size by giving the value like this context.font = "25px Satisfy";
When clicking on the button, first we are going to check if the text field is empty or not. If not then get the text from the text field and pass it to that function like that startDraw(source_text);
So here is the full code.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Add Text to Image using jquery</title>
</head>
<body>
<canvas id="pic_canvas"></canvas>
<input type="text" class="form-control" id="source_text">
<button class="btn btn-success" id="addBtn">Add Text</button>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var base_img = "https://codehasbug.com/wp-content/uploads/2021/06/good-morning.jpg";
var imageObj = new Image();
var imgWidth;
var imgHeight;
var canvas = document.getElementById("pic_canvas");
var source_text = "";
$("#addBtn").click(function(){
source_text = $("#source_text").val();
if(source_text){
startDraw(source_text);
}else{
alert("you have to write text");
}
});
function startDraw(data){
imageObj.src = base_img;
imageObj.onload = function(){
imgWidth = imageObj.width;
imgHeight = imageObj.height;
canvas.width = imgWidth;
canvas.height = imgHeight;
var context = canvas.getContext("2d");
context.clearRect(0, 0, imgWidth, imgHeight);
context.drawImage(imageObj, 0, 0, imgWidth, imgHeight);
context.font = "25px Satisfy";
context.fillStyle = "#fff";
data = data.replace(/\+/g, ' ');
context.fillText(decodeURIComponent(data), 70, 280);
};
}
/***
* add google font asynchronously
*/
// load google font == Satisfy
WebFontConfig = {
google:{ families: ['Satisfy'] },
active: function(){startDraw(source_text);},
};
(function(){
var wf = document.createElement("script");
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js';
wf.async = 'true';
document.head.appendChild(wf);
})();
})
</script>
</body>
</html>
Check JSFiddle.