旋转HTML画布文本

时间:2019-06-05 08:52:46

标签: javascript html canvas

我有一个矩形,其边缘带有标记为150的文本

如何旋转文本“ 150”以从下至上阅读。下面的代码使150沿边缘从上到下看。

预期在上方 enter image description here

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

const x = 150;
const y = 150;
const w = 200;
const h = 150;

ctx.fillStyle = "gray";
ctx.fillRect(x + 0.5, y + 0.5, w, h);
ctx.font = "12px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("Rectangle", x + w / 2, y + h / 2);

ctx.fillText('200', x + w / 2, y + h - 5);
ctx.save();
ctx.translate(x + w, y + h / 2);

ctx.rotate(90 * Math.PI / 180);

ctx.fillText('150', 0, 0 + w - 5);
ctx.restore();
<canvas id="myCanvas" width="400" height="300"></canvas>

1 个答案:

答案 0 :(得分:2)

注意负平移和负旋转。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

const x = 150;
const y = 150;
const w = 200;
const h = 150;

ctx.fillStyle = "gray";
ctx.fillRect(x + 0.5, y + 0.5, w, h);
ctx.font = "12px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("Rectangle", x + w / 2, y + h / 2);

ctx.fillText('200', x + w / 2, y + h - 5);
ctx.save();

ctx.translate(x - w, y + h / 2);
ctx.rotate(-90 * Math.PI / 180);

ctx.fillText('150', 0, w + 15); /* 15 is width of the text itself */
ctx.restore();
<canvas id="myCanvas" width="400" height="300"></canvas>