需求:从数据库中随机获取一段话,一张图片,把两者合成一张图片。
HTML代码:
<div style="width:30%;float:left;"> <canvas id="canvas"></canvas> </div>
Js代码:
1 imgAddTextToImage(imagePath, text, date, chineseToday, dateHoliday, chineseTwentyFourDay) { 2 var canvas = document.querySelector("canvas"); 3 var context = canvas.getContext("2d"); 4 // canvas 大小 5 canvas.width = document.documentElement.clientWidth; 6 canvas.height = document.documentElement.clientHeight - 102; 7 // Draw Image function 8 var img = new Image(); 9 img.src = imagePath; 10 img.onload = function () { 11 //等比例缩小图片 12 var scale = 1; 13 var size = 750; // 可以根据具体的要求去设定 14 if (this.width > size || this.height > size) { 15 if (this.width > this.height) { 16 scale = size / this.width; 17 } else { 18 scale = size / this.height; 19 } 20 } 21 context.width = this.width * scale; 22 context.height = this.height * scale; // 计算等比缩小后图片 23 context.drawImage(img, 0, 0, context.width, context.height); 24 context.lineWidth = 1; 26 context.font = "24px 楷体"; 27 context.fillStyle = "white"; 29 context.fillText(date, 260, 640); 30 context.fillText(chineseToday, 280, 680); 31 context.fillText(dateHoliday + chineseTwentyFourDay, 280, 720); 32 var x = 30, y = 50; // 文字开始的坐标 33 var j = 0; 34 var letterSpacing = 5; // 设置字间距 35 for (var i = 0; i < text.length; i++) { 36 const str = text.slice(i, i + 1).toString(); 37 if (str.match(/[A-Za-z0-9]/) && (y < 600)) { // 非汉字 旋转 38 context.save(); 39 context.translate(x, y); 40 context.rotate(Math.PI / 180 * 90); 41 context.textBaseline = 'bottom'; 42 context.fillText(str, 0, 0); 43 context.restore(); 44 y += ctx.measureText(str).width + letterSpacing; // 计算文字宽度 45 } else if (str.match(/[\u4E00-\u9FA5]|[,.!,。!]/) && (y < 600)) { 46 context.save(); 47 context.textBaseline = 'top'; 48 context.fillText(str, x, y); 49 context.restore(); 50 y += context.measureText(str).width + letterSpacing; // 计算文字宽度 51 } else if (str.match(/[\u4E00-\u9FA5]|[,.!,。!]/) && (y > 600)) { 52 //文字换行 53 if (i - j == 22) { 54 j = i; 55 x = x + 40; 56 y = 40 + i + 10; 57 } 58 context.save(); 59 context.textBaseline = 'top'; 60 context.fillText(str, x, y); 61 context.restore(); 62 y += context.measureText(str).width + letterSpacing; // 计算文字宽度 63 } 64 } 65 }; 66 },
效果展示: