Friends, i’m finding rotating a text canvas object a bit tricky. The thing is, I’m drawing a graphic, but sometimes the width of each bar is smaller than the ‘value’ of that bar. So I have to ratate the ‘value’ 90 degrees. It will work in most cases.
I am doing the following
a function(x, y, text, maxWidth...)
var context = this.element.getContext('2d');
var metric = context.measureText(text); //metric will receive the measures of the text
if(maxWidth != null){
if(metric.width > maxWidth) context.rotate(Math.PI / 2);
}
context.fillText(text, x, y);
Ok, but it doesn’t really work. Problems that I have seen: The text duplicates in different angles. The angles are not what I want (perhaps just a matter of trigonometry).
Well I just don’t know what to do. I read something about methods like ‘save’ and ‘restore’ but I don’t what to do with them. I’ve made some attempts but no one worked.
Would you help me with this, guys?
This is a bit tricky to answer simply because there are a lot of concepts going on, so I’ve made you an example of what I think you’d like to do here:
http://jsfiddle.net/5UKE3/
The main part of it is this. I’ve put in a lot of comments to explain whats going on:
To rotate around the right spot you have to translate to that spot, then rotate, then translate back.
Once you rotate the canvas the context is rotated forever, so in order to stop all your new drawing operations from rotating when you dont want them to, you have to use
saveandrestoreto “remember” the normal, unrotated context.If anything else doesn’t make sense let me know. Have a good time making canvas apps!