如何使用jquery在图片上动态添加文字(附代码)

563 阅读3分钟

总结

在本教程中,我们将看到如何使用jQuery在图片上添加文本水印或动态文本

在PHP中,我们可以通过使用imagettftext轻松插入文本。但在jQuery中,这就有些棘手了。所以让我们看看如何创建这个。

概述

  1. 首先,在你的项目中添加jQuery。这里我也使用了Bootstrap。但这个项目不需要它。
  2. 添加一个canvas元素,并给出一个idpic_canvas
  3. 同时,添加一个文本输入字段和一个按钮,并给每个元素赋予id,即source_textaddBtn
  4. 取一个你想插入文本的图片URL,并将其存储在base_img变量中。
  5. 加载字体文件。我使用的是Google Satisfy字体
  6. 编写一个名为**startDraw()**的函数,将文本写入图片中。
  7. 每当用户点击AddText按钮时,调用上述函数。

第1步:在你的项目中添加jQuery需求元素

首先,我们要把jQuery添加到我们的项目中。我在这里使用的是Bootstrap。所以复制Bootstrap的模板代码。同时,添加画布,文本输入和按钮元素:

<!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>

第2步:添加图片,文本将被显示

我们用一个叫base_img的变量来存储我们的图片来源:

var base_img = "https://codehasbug.com/wp-content/uploads/2021/06/good-morning.jpg";

同时我们需要一个图像对象。因此,创建一个图像对象和两个变量ImgWidthImgHeight。这两个变量将存储图像的高度和宽度。

第3步:创建一个空白画布

我们还需要一个空白画布。因为图像和文字将被写在这个画布上。因此,通过我们在步骤1中已经添加的id "pic_canvas "选择画布,并将其存储在画布变量中:

var canvas = document.getElementById("pic_canvas");

第4步:动态加载谷歌字体

在这里,我们使用谷歌字体,名为Satisfy。但我们不是在标题部分或使用CSS来链接字体,而是通过动态方式将其包含在内。所以让我们先检查一下代码:

// 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);
})();

在上面的代码中,你可以看到我们已经创建了一个匿名函数。在它里面,我们创建了一个脚本标签,并将其存储在wf变量中。之后,我们给它的src属性分配了https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js

现在我们将async属性设置为 "true",并将其添加到head部分。在WebFontConfig部分,我们将字体家族设置为Satisfy。但在回调部分,我们调用了一个参数为source_text的函数startDraw。在下一步,我将讨论如何创建上述函数。

第5步:创建startDraw函数

所以让我们先检查一下代码:

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);
		
	};
	
}

在第2步中,我们已经创建了一个图像对象,即imageObj。现在我们需要将它的src属性设置为base_img,在这里我们已经存储了我们的图像路径。

由于从URL加载图片需要一定时间,我们将使用onload方法。这意味着每当图像被加载时,都会引发onload事件。

现在我们必须用图像的高度和宽度来指定画布的高度和宽度。然后使用drawImage在画布上绘制imageObj

第一次加载页面时,我们没有直接调用startDraw()函数。这是因为我们不知道字体何时会被加载。所以我们从WebFontConfig部分调用这个函数。

你可以像这样通过给出数值来设置字体大小context.font = "25px Satisfy";

第6步:点击按钮时调用startDraw()函数

当点击按钮时,首先我们要检查文本字段是否是空的。如果不是,则从文本字段 ,并将其传递给该函数,如startDraw(source_text)。

因此,这里是完整的代码:

<!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>