虽然这是对前一个答案的跟进,但它增加了一点(希望如此) .
主要是我想澄清的是,通常我们会想到绘制像 draw a rectangle at 10, 3 这样的东西 .
所以如果我们这样考虑: move origin to 10, 3 ,那么 draw rectangle at 0, 0 . 然后我们要做的就是在两者之间添加一个旋转 .
另一个重点是文本的对齐 . 最简单的方法是在0,0处绘制文本,因此使用正确的对齐方式可以让我们在不测量文本宽度的情况下执行此操作 .
我们仍然应该将文本移动一定量以使其垂直居中,并且不幸的是画布没有很好的线高支持,所以这是一个猜测和检查的事情(如果有更好的东西,请纠正我) .
我创建了3个示例,提供了一个点和一个带有3个对齐的文本,以显示屏幕上的实际点是字体的位置 .
var font, lineHeight, x, y;
x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';
// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
this.context.fillText('right', 0, lineHeight / 2); 行基本上是 0, 0 ,除了我们略微移动文本在点附近居中