canvas——竖排字

57 阅读1分钟
    let name =
        `这是需要竖排的文字内容,如果是yingwen的话则会旋转`; // 文本内容
    let x = this.canvasWidth - 110,
        y = 50; // 文字开始的坐标
    let letterSpacing = 2; // 设置字间距
    ctx.setFontSize(12)
    for (let i = 0; i < name.length; i++) {
        const str = name.slice(i, i + 1).toString();
        console.log(str);
        if (y > this.canvasHeight - 60) {
            y = 50
            x -= 15
        }
        if (str.match(/[\u4E00-\u9FA5]/)) {
            ctx.save();
            ctx.textBaseline = 'top';
            ctx.fillText(str, x, y);
            ctx.restore();
            y += ctx.measureText(str).width + letterSpacing; // 计算文字宽度
        } else {
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(Math.PI / 180 * 90);
            ctx.textBaseline = 'bottom';
            ctx.fillText(str, 0, 0);
            ctx.restore();
            y += ctx.measureText(str).width + letterSpacing; // 计算文字宽度
        }

    }

    ctx.draw()