12e3

/**
 * 绘制canvas
 */
function draw(name='大威德', score = 23, level = 1, str = '哈哈哈哈') {
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    // 绘制背景
    var img = new Image();
    img.src = "images/newbg.jpg";
    img.onload = function () {
        ctx.drawImage(img, 0, 0,375,640);
        // 绘制底部文字
        ctx.font = "bold normal 20px Microsoft YaHei";
        ctx.fillStyle = "black";
        ctx.fillText(name, 375 * 0.18, 640 * 0.34);
        ctx.font = "bold normal 20px Microsoft YaHei";
        ctx.fillStyle = "red";
        ctx.fillText(score, 375 * 0.63, 640 * 0.345);
        ctx.fillStyle = "black";
        ctx.fillText(level, 375 * 0.37, 640 * 0.458);
        ctx.font = "normal 18px Microsoft YaHei";
        ctx.fillStyle = "black";
        // 绘制多行文字
        canvasTextAutoLine(str, c, 375 * 0.1, 640 * 0.5, 20);
        
    };

}
/*
str:要绘制的字符串
canvas:canvas对象
initX:绘制字符串起始x坐标
initY:绘制字符串起始y坐标
lineHeight:字行高,自己定义个值即可
*/
function canvasTextAutoLine(str, canvas, initX, initY, lineHeight) {
    var ctx = canvas.getContext("2d");
    var lineWidth = 0;
    var canvasWidth = document.documentElement.clientWidth;
    var lastSubStrIndex = 0;
    for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth * 0.8) {//减去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);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/teamemory/p/9771512.html
123