Skip to content

1. 文本和定位

文本在节点上的位置可以调整。

文字定位由三个核心属性控制:1. 位置 2. 文本对齐方式 2. 文本基线

  1. 位置表示如下图:

灰色矩形区域代表节点,节点文本的位置默认在下面中间(cb)的位置。

  1. 文本对齐方式如下图:
  1. 文本基线如下图:
  1. 自定义偏移量 除上述三种方式,还可以通过设置:textOffsetXtextOffsetY 属性来设置文本的水平和垂直偏移量。

下面的代码展示了不同位置和对齐方式的组合:

js
// 文字定位由三个属性:1. 位置 2. 文本对齐方式 2. 文本基线
// 教程:http://www.jtopo.com/tutorial.html#41-文本和定位
// 参考:HTML5-Canvas:https://www.w3school.com.cn/tags/canvas_textbaseline.asp

/*
 * 位置表示: 水平(left-center-right) 垂直(top-middle-bottom)
 * lt : left-top	左上
 * ct : center-top  正上
 * rt : right-top   右上
 
 * lm : left-middle  左中
 * center : center   正中-中心
 * rm : right-bottom 右中
 * 
 * lb : left-bottom   左下
 * cb : center-bottom 正下
 * rb : right-bottom  右下
 * 
 */
let positions = [
  'lt', 'ct', 'rt', 
  'lm', 'center', 'rm', 
  'lb', 'cb', 'rb'];

let textAligns = ['center', 'left', 'right'];

let textBaselines = ['top', 'middle', 'bottom'];

node.css({
    backgroundColor: randomColor(),
    textPosition: positions[0],
    textAlign: textAligns[0],
    textBaseline: textBaselines[0],
    fontColor: 'black',
});

// 更细致的控制:水平和垂直方向的偏移量。
node.style.textOffsetX = 5;
node.style.textOffsetY = 5;

效果参考: