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

当前功能的运用场景是:用户需要传文件给他人,在用户选择文件之后需要显示一个文件图标和所选文件的名称。

当前代码部分是摘自网上,但是已经忘记在什么地方获取的,如有侵权联系小弟后自当删除。

注意:必须在html页面里面内置一个canvas

class Text2Img {

    //当前画布的ID
    private static CanvasId: string = "canvas";

    //设置画布ID
    public 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
        };
    }
}

  

posted @ 2017-06-27 14:54  RoseNix  阅读(746)  评论(0编辑  收藏  举报