回答这个问题有点棘手,因为涉及到很多概念,所以我给你举了一个我认为你想在这里做的例子:
http://jsfiddle.net/5UKE3/ http://jsfiddle.net/5UKE3/
其主要部分是这样的。我已经发表了很多评论来解释发生了什么:
function drawSomeText(x, y, text, maxWidth) {
//metric will receive the measures of the text
var metric = ctx.measureText(text);
console.log(metric.width);
ctx.save(); // this will "save" the normal canvas to return to
if(maxWidth != null && metric.width > maxWidth) {
// These two methods will change EVERYTHING
// drawn on the canvas from this point forward
// Since we only want them to apply to this one fillText,
// we use save and restore before and after
// We want to find the center of the text (or whatever point you want) and rotate about it
var tx = x + (metric.width/2);
var ty = y + 5;
// Translate to near the center to rotate about the center
ctx.translate(tx,ty);
// Then rotate...
ctx.rotate(Math.PI / 2);
// Then translate back to draw in the right place!
ctx.translate(-tx,-ty);
}
ctx.fillText(text, x, y);
ctx.restore(); // This will un-translate and un-rotate the canvas
}
要围绕正确的点旋转,您必须平移到该点,然后旋转,然后平移回来。
一旦旋转画布,上下文就会旋转forever,因此,为了在您不希望旋转时阻止所有新的绘图操作旋转,您必须使用save
and restore
“记住”正常的、未旋转的上下文。
如果还有其他事情没有意义,请告诉我。祝您制作画布应用程序愉快!