canvas生成表单海报
项目需要输入表单生成图片,可以使用下面方法生成海报,保存到手机,话不多说,上代码吧
HTML部分代码
<div class="dd"> <img src="images/bg2021.jpg" alt=""> <input type="text" class="username" id="username"> <input type="text" class="tel" maxlength="11" id="tel"> <input type="text" class="num" id="num"> <input type="text" class="time" id="time"> <button type="button" class="save" onclick="save()">提交生成</button> </div> <div id="app" class="app"> <div id="appmin" class="appmin"> </div> </div>
js部分代码
<script> function save(){ let canvas = document.createElement('canvas') canvas.width = "375" canvas.height = "667" //创建画布,并设置宽高 let ctx = canvas.getContext("2d") //背景图 var bgImg = './images/bg2021.jpg'; //随机背景图 var username = $('#username').val(); var tel = $('#tel').val(); var num = $('#num').val(); var time = $('#time').val(); loadImg([ bgImg ]).then(([img1])=> { ctx.drawImage(img1, 0, 0, 1080, 1920) //画布上先绘制背景图` //文字大小 ctx.font="52px Microsoft YaHei"; //字符str //位置100,100 ctx.fillText(username,266,920); ctx.fillText(tel,266,1050); ctx.fillText(num,326,1170); ctx.font="45px Microsoft YaHei"; ctx.fillText(time,370,1290); imageURL = canvas.toDataURL("image/png") //获取图片合并后的data-URL,参数可选图片格式,图片质量,详自查API` let img3 = new Image() $('#app').fadeIn(); document.getElementsByClassName("appmin")[0].append(img3) img3.src = imageURL canvas.style.display = "none" $("#appmin").append(" <p>生成成功!长按图片保存</p><img src='images/close.png' class='close' onclick='colse()'/>") }); } function loadImg(src) { let paths = Array.isArray(src) ? src : [src] let promise = paths.map((path) => { return new Promise((resolve, reject) => { let img = new Image() img.setAttribute("crossOrigin", 'anonymous') img.src = path //只是更新了DOM对象,图片数据信息还未加载完成,加载资源是异步执行的,需要监听load事件的,事件发生后,就能获取资源 img.onload = () => { resolve(img) } img.onerror = (err) => { alert('图片加载失败') } }) }) return Promise.all(promise) } function colse(){ $("#appmin").html('') $("#app").fadeOut(); } </script>
通过canvas画布生成图片,如有写的不到位还请大家指正,共同进步,奥利给!!!
本文来自博客园,作者:喆星高照,转载请注明原文链接:https://www.cnblogs.com/houxianzhou/p/15825105.html