点击查看html编辑器说明文档

在 JS 中调整 canvas 里的文字间距edit icon

|
|
Fork(复制)
|
|
作者:
lynn-ssk
提交反馈
嵌入
设置
下载
HTML
格式化
支持Emmet,输入 p 后按 Tab键试试吧!
<head> ...
展开
</head>
<body>
<canvas id="canvas" width='440' height="130"></canvas>
</body>
CSS
格式化
JS
格式化
/**
 * 绘制带间距的文字
 * @param text 要绘制的文字
 * @param x 绘制的位置 x
 * @param y 绘制的位置 y
 * @param spacing 文字间距
 */
CanvasRenderingContext2D.prototype.fillTextWithSpacing =
function(text,x,y,spacing=0){
    // 如果间距为0,则不用对每个字符单独渲染以节省性能
    if(spacing === 0){
        this.fillText(text,x,y);
        return;
    }

    let totalWidth = 0; // 已渲染字符所占用的宽度
    // 对每个字符单独渲染
    for(let i=0; i<text.length; i++){
        this.fillText(text[i],totalWidth,y);
        //累计已占用宽度
        totalWidth += ctx.measureText(text[i]).width + spacing;
    }
}

//创建画布
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

//定义文字样式
ctx.font = "bold 40px caption";
ctx.fillStyle = "#54a8eB";

//绘制文字
ctx.fillText('正常间距 - 阳光知道', 0, 40);
ctx.fillTextWithSpacing('扩大间距 - 阳光知道', 0, 80, 6);
ctx.fillTextWithSpacing('缩小间距 - 阳光知道', 0, 120, -5);
预览
控制台