虽然这是对上一个答案的跟进,但它增加了一点(希望如此)。
我主要想澄清的是,通常我们会想到画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,除了我们稍微移动以使文本在该点附近居中