Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hawx1993 opened this issue Mar 17, 2017 · 0 comments
Open

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

hawx1993 opened this issue Mar 17, 2017 · 0 comments

Comments

@hawx1993
Copy link
Owner

hawx1993 commented Mar 17, 2017

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绘图很重要的一点是需要等待所有图片都加载完毕再调用绘图方法。

后续更新

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant