Drawing rotated text on a HTML5 canvas

Part of a web application I’m developing requires me to create bar graphs to display various information. I figured, if the user’s browser is capable, I would draw them using the HTML5 canvas element. I have no problem drawing lines and bars for my graphs, but when it comes to labeling the axes, the bars, or the lines I ran into a snag. How do I draw rotated text onto a canvas element so that it lines up with the item it is labeling? A couple examples include:

  • Rotate text 90 degrees counter clockwise to label the y-axis
  • Rotate text 90 degrees counter clockwise to label bars on a vertical bar graph
  • Rotate text an arbitrary amount to label lines on a line graph

Any pointers would be appreciated.


Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn’t too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:


The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

Please see the answer below for a more complete solution.