前端js用canvas合成图片并转file对象
强大的前端js可以做很多东西,今天用canvas
合成图片并添加文字,然后转成file对象
进行上传。代码如下:
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
</head>
<body><canvas id="myCanvas"></canvas>
</body>
<script>window.onload = function() {// 获取Canvas元素var canvas = document.getElementById('myCanvas');var ctx = canvas.getContext('2d');// 创建新的Image对象var bgimg = new Image();bgimg .crossOrigin = "Anonymous"; // 加这句// 设置图片源地址//bgimg.src = 'https://q5.itc.cn/q_70/images03/20240406/2c8f1d2cd13e4d4392fa07ccaab1f219.jpeg';bgimg.src = 'https://yueuat.obs.cn-south-1.myhuaweicloud.com/images/2024/11/b055493ee430441abc276d2166a04473.jpg'// 当图片加载完成后,将其绘制到Canvas上bgimg.onload = function() {// 设置Canvas的宽高,如果不设置,默认以图片的尺寸显示canvas.width = bgimg.width;canvas.height = bgimg.height;// 将图片绘制到Canvas上ctx.drawImage(bgimg, 0, 0);// 合并图片var img1 = new Image();//img1.src = 'https://q5.itc.cn/q_70/images03/20240406/2c8f1d2cd13e4d4392fa07ccaab1f219.jpeg';img1.src = 'https://yuedev.obs.cn-south-1.myhuaweicloud.com/DSC_0029.JPG';img1.onload = function() {// 将图片绘制到bgimg上// 横图 等比例缩小 上下居中绘制var width = bgimg.width / 2;var height = (width * img1.height) / img1.width;ctx.drawImage(img1, 0, (bgimg.height / 2) - (height / 2),width,height);}// 添加文字ctx.font = '50px Arial';ctx.fillStyle = '#000';var txt = "那是一个阳光明媚的上午十点,我和\n越添科技的伙伴们一同来到了\n深圳的心智青老年大学,开展一\n场特别的梦想。";var txtX = (bgimg.width / 2) + 300;text(ctx,txt,txtX,600,(bgimg.width - txtX - 300),100);// 创建Blob对象canvas.toBlob(blob => {const file = new File([blob], "canvas.png", {type: "image/png"});// file对象可在这里进行上传console.log(11111,file);});};/** 绘制自动换行文字* @param ctx 画布上下文* @param text 文字* @param x 坐标x* @param y 坐标y* @param maxWidth 文字最大宽度(0表示竖排显示)* @param maxWidth 文字行高* @param split 按照指定符号切割成段落*/function text(ctx,text,x=0,y=0,maxWidth=300,lineHeight=20,split="\n"){// 将文本分割成多个段落var paragraph = text.split(split);for(var k = 0; k < paragraph.length; k++) {if(k != 0){y += lineHeight;}var lines = paragraph[k].split('');var line = "";for(var i = 0; i < lines.length; i++) {line += lines[i];if(ctx.measureText(line).width > maxWidth){line = lines[i];y += lineHeight;}ctx.fillText(line, x, y);}}}}
</script>
</html>
到此完成,跑一下看看是不是可以了。