我认为翻译和转换到上下文就像操作覆盖在画布上的坐标网格一样。默认情况下,原点(0,0)从画布的左上角开始。X 从左到右增加,Y 从上到下增加。如果你在你的左手上画一个“ L”,你的食指和拇指放在你的前面,拇指会指向增加 Y 的方向,而你的食指会指向增加 X 的方向。我知道这是基本的,但是我发现在思考平移和旋转时它很有帮助。原因如下:
翻译上下文时,将坐标网格的原点移动到画布上的新位置。当你旋转上下文的时候,想象一下你用左手在一个顺时针方向上旋转“ L”,这个“ L”是用弧度表示的。当您使用 strokeText 或 filText 时,请指定与新对齐的轴相关的坐标。为了让你的文本从下到上都可读,你需要将文本翻译到下面的位置,在这个位置开始标签,旋转 -90度,填充或者笔画文本,沿着旋转的 x 轴偏移每个标签。这种方法应该可行:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var font, text, x, y;
text = "Mississippi";
//Set font size before measuring
font = 20;
ctx.font = font + 'px Arial, sans-serif';
//Get width of text
var metrics = ctx.measureText(text);
//Set canvas dimensions
c.width = font;//The height of the text. The text will be sideways.
c.height = metrics.width;//The measured width of the text
//After a canvas resize, the context is reset. Set the font size again
ctx.font = font + 'px Arial';
//Set the drawing coordinates
x = font/2;
y = metrics.width/2;
//Style
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = "bottom";
//Rotate the context and draw the text
ctx.save();
ctx.translate(x, y);
ctx.rotate(-Math.PI / 2);
ctx.fillText(text, 0, font / 2);
ctx.restore();