分享一款利用HTML5实现的自定义文字背景应用,首先我们可以输入需要显示的文字,并且为该文字选择一张背景图片,背景图片就像蒙版一样覆盖在文字上。点击生成QQ签名档即可将文字背景融为一体生成另外一张图片,你也可以下载这张拥有你QQ签名档的图片。
实现的代码。
html代码:
<canvas id="mycanvas" width="1280" height="512"></canvas> 内容:<input type="text" id="mytxt1" value="HTML5TRICKS" /> 文字背景图:<select id="dbg"> <option value="bg4.png">bg4.png</option> <option value="bg5.png">bg5.png</option> </select> <input type="button" id="send" value="生成签名档" /> <a href="#" id="imgdownload">下载图片</a> <script> var mycanvas = document.getElementById("mycanvas"); var mytxt1 = document.getElementById("mytxt1"); var dbg = document.getElementById("dbg"); var imgdownload = document.getElementById("imgdownload"); var ctx = mycanvas.getContext("2d"); var bg = new Image(); var bg2 = new Image(); bg.src = 'imgs/bg3.png'; bg2.src = 'imgs/bg4.png'; bg2.onload = ShowImg; function ShowImg() { bg2.src = 'imgs/' + dbg.value; ctx.drawImage(bg, 0, 0, mycanvas.width, mycanvas.height); ctx.save(); var fpadd = 200; //规定内间距 var fsz = Math.ceil((mycanvas.width - fpadd * 2) / mytxt1.value.length); //根据字数计算字体大小 ctx.font = fsz + "px hychf"; var tw = ctx.measureText(mytxt1.value).width; //文字真实宽度 var ftop = (mycanvas.height - fsz) / 2 - 30; //根据字体大小计算文字top var fleft = (mycanvas.width - tw) / 2 + 16; //根据字体大小计算文字left ctx.textBaseline = "top"; //设置绘制文本时的文本基线。 var woodfill = ctx.createPattern(bg2, "repeat"); //设置图片为笔刷 ctx.fillStyle = woodfill; ctx.shadowBlur = 10; //阴影程度 ctx.shadowOffsetX = 20; ctx.shadowOffsetY = 20; ctx.shadowColor = "rgba(0,0,0,1)"; ctx.fillText(mytxt1.value, fleft, ftop); ctx.lineWidth = 1; ctx.strokeStyle = "rgba(255,255,255,0.4)"; ctx.strokeText(mytxt1.value, fleft, ftop); ctx.restore(); } document.getElementById("send").onclick = ShowImg; imgdownload.onclick = function () { if (!mytxt1.value) { alert('请输入内容'); return false; } this.href = mycanvas.toDataURL(); this.target = "_blank"; this.download = mytxt1.value + ".png"; } </script>
css代码:
body { background-color: #ddd; -webkit-user-select: none; font-family: hychf, "黑体"; margin: 0; } @font-face { font-family: hychf; src: url('fonts/hychf.ttf'); } canvas { border: 1px solid #777; display: block; margin: auto; } #imgdownload { width: 100px; height: 30px; display: block; text-decoration: none; text-align: center; line-height: 30px; border: 1px solid #000; border-radius: 6px; }
via:http://www.w2bc.com/Article/25804