HTML5文本画布旋转的情况下,文本宽度大于最大宽度允许
HTML5 Text Canvas rotate in case text width is larger than maximum width allowed
朋友们,我发现旋转文本画布对象有点棘手。问题是,我正在绘制图形,但有时每个条的宽度小于该条的"值"。所以我必须用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
}
要绕正确的位置旋转,你必须先平移到那个位置,然后旋转,然后再平移回来。
一旦你旋转画布,上下文就会永远旋转,所以为了阻止所有新的绘图操作在你不希望它们旋转的时候旋转,你必须使用save
和restore
来"记住"正常的,未旋转的上下文。
如果还有什么不明白的,请告诉我。祝你制作画布应用程序愉快!
相关文章:
- 如何使用jquery在填充自动完成的值后使文本框只读
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 用程序搜索JQuery数据表中的文本
- jQuery匹配JSON对象的部分文本
- onkeyup无法动态创建多个文本区域
- 如何在下面的ES6循环中获得前面的文本
- 每次文本长度大于 2 行时,都会出现“阅读更多”按钮
- AngularJs输入文本框只允许大于零值
- 拉伸文本..如果在 Html5 画布中长度大于 10
- ASP.NET 如果文本在“大于”和“小于”符号之间给出,则无法保存文本框
- 当输入类型文本小于 0 或大于 24 时,如何禁用输入类型按钮
- 验证不允许大于数字的文本框
- 当文本值大于$40时为模态-jQuery
- “大于”的意外结果比较文本输入的值
- 防止粘贴长度大于给定限制的文本
- HTML5文本画布旋转的情况下,文本宽度大于最大宽度允许
- 文本输入值大于10不大于5000 jQUERY
- 如果文本框中的值大于1,则更改为复数
- 如何在文本区域的文本长度大于52时增加其行数?