将文本标签沿着一条线放在画布上 [英] Placing text label along a line on a canvas
问题描述
我设法使用html5在画布上画一条线:
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?
推荐答案
我已经创建了一个例子我的网站。一般来说,您希望:
I have created an example of this on my website. In general, you want to:
-
translate
然后 -
旋转
上下文的金额(以弧度为单位),然后 -
fillText
正常。
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.
function drawLabel( ctx, text, p1, p2, alignment, padding ){
if (!alignment) alignment = 'center';
if (!padding) padding = 0;
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
var p, pad;
if (alignment=='center'){
p = p1;
pad = 1/2;
} else {
var left = alignment=='left';
p = left ? p1 : p2;
pad = padding / Math.sqrt(dx*dx+dy*dy) * (left ? 1 : -1);
}
ctx.save();
ctx.textAlign = alignment;
ctx.translate(p.x+dx*pad,p.y+dy*pad);
ctx.rotate(Math.atan2(dy,dx));
ctx.fillText(text,0,0);
ctx.restore();
}
对于Firefox,您还可以选择使用 mozTextAlongPath
。
For Firefox only you also have the option of using mozTextAlongPath
.
这篇关于将文本标签沿着一条线放在画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!