欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

使用的是html5的canvas将文字转换成图片

发布时间:2025/5/22 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 使用的是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将文字转换成图片的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。