Поворот HTML-текста холста - PullRequest
2 голосов
/ 05 июня 2019

У меня есть прямоугольник с текстом, помеченным 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 Ответ

2 голосов
/ 05 июня 2019

Обратите внимание на отрицательный перевод и отрицательное вращение.

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...