HTML5文本画布旋转,以防文本宽度大于允许的最大宽度

Vic*_*ira 3 javascript html5 text canvas rotation

朋友们,我发现旋转文本画布对象有点棘手.问题是,我正在绘制图形,但有时每个条的宽度小于该条的"值".所以我必须将"价值"提高90度.它适用于大多数情况.

我正在做以下事情

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);
Run Code Online (Sandbox Code Playgroud)

好的,但它确实不起作用.我看到的问题:文本以不同的角度重复.角度不是我想要的(也许只是三角学的问题).

好吧,我只是不知道该怎么做.我读过一些关于"保存"和"恢复"等方法的内容,但我不知道如何处理它们.我做了一些尝试,但没有人工作.

伙计们,你能帮助我吗?

Sim*_*ris 9

回答这个问题有点棘手,因为有很多概念在继续,所以我已经让你成为我认为你想在这里做的事情的一个例子:

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
}
Run Code Online (Sandbox Code Playgroud)

要围绕右侧点旋转,您必须转换到该点,然后旋转,然后平移.

旋转画布后,上下文将永远旋转,因此,为了阻止所有新的绘制操作在您不希望的情况下旋转,您必须使用saverestore"记住"正常的,未旋转的上下文.

如果其他任何事情没有意义,请告诉我.玩得开心,制作帆布应用!