Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

javascript - How to Make Canvas Text Selectable?

Any suggestion is highly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Text selection has many components to it some visual, some non-visual.

First, make text selectable you must keep an array, of where the text is, what the text is, and what font was used. You will use this information with the Canvas function measureText.

By using measureText, with your text string, you can identify what letter the cursor should land on when you click on an image.

ctx.fillText("My String", 100, 100);
textWidth = ctx.measureText("My String").width;

You will still have to parse the font height from the "font" property, as it is not currently included in text metrics. Canvas text is aligned to the baseline by default.

With this information, you now have a bounding box, which you can check against. If the cursor is inside of the bounding box, you now have the unfortunate task of deducing which letter was intentionally selected; where the start of your cursor should be placed. This may involve calling measureText several times.

At that point you know where the cursor should go; you will need to store your text string as a text string, in a variable, of course.

Once you have defined the start and stop points of your range, you have to draw a selection indicator. This can be done in a new layer (a second canvas element), or by drawing a rectangle using the XOR composition mode. It can also be done by simply clearing and redrawing the text on top of a filled rectangle.

All told, text selection, text editing in Canvas are quite laborious to program, and it would be wise to re-use components already written, Bespin being an excellent example.

I'll edit my post should I come across other public examples. I believe that Bespin uses a grid-based selection method, possibly requiring a monospaced font. Ligatures, kerning, bi-directionality and other advanced features of font rendering require additional programming; it's a complex problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...