将文本与一条线平行对齐

Align text parallel with a line

我一直在尝试在 Canvas 中以奇怪的角度绘制三角形,但我不知道如何将文本与线条本身对齐。我该怎么做?

我用于三角形的代码是:

 
 
function init()
{
var canvas = document.getElementById("canvas");
if(canvas.getContext)
{
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,50);
ctx.lineTo(300,40);
ctx.closePath();
ctx.fill();
}
}
onload=init;

让你开始......

这是一种方法:

  1. 使用Math.atan2求直线的角度。

    // where x0,y0 is the line startpoint and x1,y1 is the endpoint
    var angle = Math.atan2( y1-y0, x1-x0 );
    
  2. context.translate(x0,y0)到直线起点

  3. context.rotate(angle) 到 #1 中找到的角度。
  4. 设置 context.textBaseline='bottom' 以便在其基线底部绘制文本。
  5. context.fillText('Your text',0,0) 沿线的角度绘制文本。
  6. 使用 context.setTransform(1,0,0,1,0,0) 撤消转换。

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.textBaseline='bottom';

var x0=50;
var y0=100;
var x1=150;
var y1=50;

ctx.beginPath();
ctx.moveTo(x0,y0);
ctx.lineTo(x1,y1);
ctx.stroke();

textOnLine('Hello, World!',x0,y0,x1,y1);

function textOnLine(text,x0,y0,x1,y1){
  var angle=Math.atan2(y1-y0,x1-x0);
  ctx.translate(x0,y0);
  ctx.rotate(angle);
  ctx.fillText(text,0,0);
  ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>