使用的是html5的canvas将文字转换成图片
生活随笔
收集整理的這篇文章主要介紹了
使用的是html5的canvas将文字转换成图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當前功能的運用場景是:用戶需要傳文件給他人,在用戶選擇文件之后需要顯示一個文件圖標和所選文件的名稱。
當前代碼部分是摘自網上,但是已經忘記在什么地方獲取的,如有侵權聯系小弟后自當刪除。
注意:必須在html頁面里面內置一個canvas
class Text2Img {//當前畫布的IDprivate static CanvasId: string = "canvas";//設置畫布IDpublic static SetCanvasId(id: string) {this.CanvasId = id;}//文字字號public static FontSize: number = 12;//空白的高度public static BlankHeight: number = 60;static reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");//判斷是否是漢字static CheckChinese(val): any {return this.reg.test(val);}/*轉換成圖片*/public static ToImg(txt: string) {var len = txt.length;//英文和中文的文字數目let chinese = 0, let english = 0;for (var j = 0; j < txt.length; j++)this.CheckChinese(txt[j]) ? chinese++ : english++;var canvas = document.getElementById(Text2Img.CanvasId);canvas.width = Text2Img.FontSize * chinese * 1.5 + Text2Img.FontSize * english / 2;canvas.height = Text2Img.FontSize * (3 / 2) * (Math.ceil(txt.length / len) + txt.split('\n').length - 1) + Text2Img.BlankHeight;var context = canvas.getContext('2d');context.clearRect(0, 0, canvas.width, canvas.height);context.fillStyle = "#000";context.font = 'normal ' + Text2Img.FontSize + 'px 微軟雅黑';context.textBaseline = 'top';//canvas.style.display = 'none';var i = 0;function fillTxt(text) {while (text.length > len) {var txtLine = text.substring(0, len);text = text.substring(len);context.fillText(txtLine, 0, Text2Img.FontSize * (3 / 2) * i++, canvas.width);}context.fillText(text, 0, (Text2Img.BlankHeight - 10) + Text2Img.FontSize * (3 / 2) * i, canvas.width);}var txtArray = txt.split('\n');for (var j = 0; j < txtArray.length; j++) {fillTxt(txtArray[j]);context.fillText('\n', 0, Text2Img.FontSize * (3 / 2) * i++, canvas.width);}//var imageData = context.getImageData(0, 0, canvas.width, canvas.height);//返回一個base64圖片地址和圖片的長度return {Url: canvas.toDataURL("image/png"),ImageWidth: canvas.width,ImageHeight: canvas.height};} }
轉載于:https://www.cnblogs.com/kimbosung/p/7085216.html
總結
以上是生活随笔為你收集整理的使用的是html5的canvas将文字转换成图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有些数的阶乘不算了
- 下一篇: zookeeper web ui--gt