沿着画布上的线放置文本标签
我设法使用 html5 在画布上画一条线:
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
这有效。我现在想用文本“注释”该行。所以基本上,我希望沿线的长度出现自定义(例如我传入的任何内容)文本。困难在于该线可以以任何方向出现(例如具有任何斜率),因此文本需要相应地定向。有什么想法如何开始吗?
I managed to draw a line on a canvas using html5:
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
This works. I now want to "annotate" the line with text. So basically, I want there to be custom (e.g. whatever I pass in) text appearing along the length of the line. The difficulty is that the line can appear in any orientation (e.g. have any slope) so the text needs to be oriented accordingly. Any ideas how to start?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在我的网站上创建了一个示例。一般来说,您需要:
翻译
到文本的锚点,然后将旋转
您想要的量(以弧度为单位),然后fillText 照常。
我已在下面包含了示例的相关部分;
我将其作为练习留给读者,以检测文本何时颠倒并根据需要进行处理。编辑:查看我网站上的源代码,以获取保持文本直立并自动截断文本的其他代码。
仅对于 Firefox,您还可以选择使用(已弃用)mozTextAlongPath
.I have created an example of this on my website. In general, you want to:
translate
the context to the anchor point of the text, thenrotate
the context by the amount (in radians) you desire, and thenfillText
as normal.I have included the relevant portion of my example below;
I leave it as an exercise to the reader to detect when the text is upside down and handle it as desired.Edit: view the source on my site for additional code that keeps the text upright and also auto-truncates it.
For Firefox only you also have the option of using(Deprecated)mozTextAlongPath
.我使用了它并且它起作用了 =) 我只是改变了一些东西,以便当我使节点旋转时,标签始终处于易于阅读的位置:
在我的重绘函数中,我放置了这样的内容:
谢谢,
Dámaris。
I used it and it worked =) I just changed something so that when I make the node spin, the label is always in a good position to be read:
In my redraw function I put something like this:
Thanks,
Dámaris.