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:
translatethe context to the anchor point of the text, thenrotatethe context by the amount (in radians) you desire, and thenfillTextas 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.