hawx1993 / tech-blog

📦My personal tech blog,not regularly update
http://sf.gg/u/trigkit4/articles
339 stars 30 forks source link

使用HTML5 canvas 绘图的一些总结 #5

Open hawx1993 opened 7 years ago

hawx1993 commented 7 years ago

canvas文本自动换行

 /* canvas文本自动换行
     * str: 文字
     * initX:字符串起始X坐标
     * initY: 字符串起始Y坐标
     * lineHeight:文字行高
     */
   var drawTextAutoLine = function (str,initX,initY,lineHeight) {
        var lineWidth = 0;
        var canvasWidth = canvas.width-40;
        var lastSubStrIndex= 0;
        for(var i=0;i < str.length;i++){
            lineWidth += ctx.measureText(str[i]).width;
            if(lineWidth > canvasWidth-initX){//减去initX,防止边界出现的问题
                ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
                initY += lineHeight;
                lineWidth = 0;
                lastSubStrIndex=i;
            }
            if(i == str.length-1){
                ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
            }
        }
    };

canvas文字超出一行省略

    //canvas文字超出一行省略
   var ellipseText = function (str, maxWidth) {
        var width = ctx.measureText(str).width;
        var ellipsis = '…';
        var ellipsisWidth = ctx.measureText(ellipsis).width;
        if (width <= maxWidth || width <= ellipsisWidth) {
            return str;
        } else {
            var len = str.length;
            while (width >= maxWidth - ellipsisWidth && len-->0) {
                str = str.substring(0, len);
                width = ctx.measureText(str).width;
            }
            return str + ellipsis;
        }
    };

其中ctx为

var canvas = document.getElementById('canvasid');
var ctx = canvas.getContext("2d")

图片跨域解决方案

image.crossOrigin = 'anonymous';// 图片跨域解决方案, 否则toDataURL方法会报跨域错误

使用canvas绘图很重要的一点是需要等待所有图片都加载完毕再调用绘图方法。

后续更新