如何使画布文本可选? [英] How to Make Canvas Text Selectable?

查看:153
本文介绍了如何使画布文本可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何建议都非常感激。

解决方案

文本选择有许多组件,一些视觉效果, / p>

首先,使文本可选,你必须保持一个数组,文本的位置,文本是什么,以及使用什么字体。您将使用此信息与Canvas函数measureText。



通过使用measureText,您的文本字符串,您可以标识光标应该着陆什么字母,当您点击

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

您仍然必须从font属性解析字体高度,
as它当前不包括在文本指标中。默认情况下,画布文本与基线对齐



使用此信息,您现在有一个边框,您可以检查。
如果光标在边框内,你现在有一个不幸的任务,推导
这个字母是故意选择;其中应放置光标的开始。这可能涉及调用measureText几次。



在这一点上,你知道光标应该在哪里;您将需要将
文本字符串作为文本字符串存储在变量中。



一旦定义了您的范围,你必须绘制
a选择指示器。这可以在新图层(第二个canvas元素)
中完成,也可以使用XOR合成模式绘制矩形。它也可以通过
来完成,只是清除和重绘在一个填充的矩形顶部的文本。



所有告诉,文本选择,文本编辑在Canvas是相当重新使用已编写的组件是明智的,Bespin是一个很好的例子。



如果我遇到其他公共例子。我相信Bespin使用基于网格的选择方法,可能需要一个等宽字体。字形,字距,双向和其他高级功能的字体渲染需要额外的编程;这是一个复杂的问题。


Any suggestion is highly appreciated.

解决方案

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.

这篇关于如何使画布文本可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆