广树
2025-01-17 22:34
@石樱灯笼:不至于……性能还是符合换代要求。
作者:广树时间:2018-05-17 12:51:26分类:JavaScript/jQuery/Vue
试着用Canvas做了时下比较流行的熊猫记仇
测试预览:
HTML:
<div class="jichou_body"> <div><canvas id="jichou"></canvas></div> <div> <textarea class="jichou_textarea" placeholder="输入想要记录的字,单行超过显示限制记得回车换行" oninput="drawJichou(this)"></textarea> </div> <div><a href="javascript:;" id="saveCanvas">保存</button></a> </div>
CSS:
.jichou_body{ text-align: center; } .jichou_textarea{ width: 416px; height: 216px; }
JS:
var imgSrc = [ "jichouimg.png"//记仇图片路径按需填写 ] var images = []; function loading(){ var imgLength = imgSrc.length; var loadingNum = 0; for(var i=0;i<imgLength;i++){ images[i] = new Image(); images[i].src = imgSrc[i]; images[i].onload = function(){ loadingNum++; if(loadingNum===imgLength){ initImg(); } } } } //以上读取图片 function initImg(){//初始化 var c=document.getElementById("jichou"); var ctx=c.getContext("2d"); ctx.fillStyle="#ffffff"; ctx.fillRect(0,0,c.width,c.height); c.width = 416;//根据记仇图片宽度写 c.height = 336;//根据记仇图片高度写 ctx.drawImage(images[0],0,0); saveCanvas(); } function drawJichou(obj){//绘制文字 var c=document.getElementById("jichou"); var ctx=c.getContext("2d"); var inputText = obj.value; var textArr = inputText.split("\n"); var h = 336; console.log(textArr); for(var i=0;i<textArr.length;i++){ h = 336+12+24*i; } c.width = 416; c.height = h; ctx.fillStyle="#ffffff"; ctx.fillRect(0,0,c.width,c.height); ctx.drawImage(images[0],0,0); for(var i=0;i<textArr.length;i++){ ctx.fillStyle="#000000"; ctx.font="16px SimSun"; ctx.fillText(textArr[i],10,336+24*i); } saveCanvas(); } function saveCanvas(){//保存图片 var canvas = document.getElementById("jichou"); var image = canvas.toDataURL("image/png"); var link = document.getElementById("saveCanvas"); link.download = "记仇.png"; link.href = image.replace("image/png", "image/octet-stream"); } loading();