HTML5文本画布旋转的情况下,文本宽度大于最大宽度允许

HTML5 Text Canvas rotate in case text width is larger than maximum width allowed

本文关键字:文本 大于 布旋转 旋转 HTML5 情况下      更新时间:2023-09-26

朋友们,我发现旋转文本画布对象有点棘手。问题是,我正在绘制图形,但有时每个条的宽度小于该条的"值"。所以我必须用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);

好的,但是它并没有真正起作用。我看到的问题:文本在不同的角度重复。角度不是我想要的(也许只是三角学的问题)。

我不知道该怎么办。我读了一些关于"保存"answers"恢复"的方法,但我不知道如何使用它们。我做了一些尝试,但都没有成功。

你们能帮我一下吗,伙计们?

回答这个问题有点棘手,因为涉及到很多概念,所以我给你举了一个例子,我认为你会在这里做的:

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
}

要绕正确的位置旋转,你必须先平移到那个位置,然后旋转,然后再平移回来。

一旦你旋转画布,上下文就会永远旋转,所以为了阻止所有新的绘图操作在你不希望它们旋转的时候旋转,你必须使用saverestore来"记住"正常的,未旋转的上下文。

如果还有什么不明白的,请告诉我。祝你制作画布应用程序愉快!