stackow101 - 5 months ago 21
HTML Question

# How rotate each figure by 90 degrees?

I'm trying to draw a coordinate system. I have a problem with the horizontal axis. I need to turn every number by 90 degrees.

my attempt:

``````  var canvasGraphElem = document.getElementById("canvasGraph");
canvasGraphElem.width = 300;
canvasGraphElem.height = 200;
var ctx = canvasGraphElem.getContext('2d');

for(var i = 0; i <= 300; i = i + 30) {
ctx.save();
ctx.font = "10px Arial";
ctx.textAlign = "right";
ctx.translate(140, 140);
ctx.rotate(-Math.PI/2);
ctx.fillText(i, 0 + i, 0 - 25);
ctx.restore();
};
``````

jsfiddle

The result should look like this:

Image is teal with numbers

You can approach this two ways:

Rotating text using local transformation. This allows you to rotate the text independently an at any angle and it's easier to place text and "logic" locations, but it requires a few more steps.

Rotate the whole context at once. This require you to "switch" axis as x axis is now y, and vica verse. It also limit the rotation to 90° and you have to think in terms of switched axis.

# Method 1

``````var ctx = document.querySelector("canvas").getContext("2d");

ctx.font = "10px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline  = "middle";

for(var i = 0; i <= 300; i += 30) {
ctx.setTransform(1, 0, 0, 1, 10 + i, 30);   // absolute transform
ctx.rotate(-Math.PI*0.25);                  // any angle (demo 45°)
ctx.fillText(i, 0, 0);
};

ctx.setTransform(1, 0, 0, 1, 0, 0);           // reset transforms``````
``<canvas></canvas>``

# Method 2

``````var ctx = document.querySelector("canvas").getContext("2d");

ctx.font = "10px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline  = "middle";
ctx.translate(20, 30);                        // set pivot
ctx.rotate(-Math.PI*0.5);                     // rotate canvas -90° around pivot

for(var i = 0; i <= 300; i += 30) {
ctx.fillText(i, 10, i);                     // increase y, since now "y=x"
};

ctx.setTransform(1, 0, 0, 1, 0, 0);           // reset transforms``````
``<canvas></canvas>``

Source (Stackoverflow)