画布元素上的 HTML 文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5278382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:18:15  来源:igfitidea点击:

HTML text field over canvas element

htmltextcanvasfield

提问by puk

I have been playing around with text in the canvas, and although it is easy to draw, it is not easy to interact with. I began implementing keyboard press functionality to update text on the canvas, but then gave up when I realized I would have to incorporate cut,copy,past and undo functionality.

我一直在画布上玩文字,虽然画起来很容易,但交互起来却并不容易。我开始实现键盘按下功能来更新画布上的文本,但当我意识到我必须合并剪切、复制、过去和撤消功能时放弃了。

Is there anyway to "float" html elements on top of eachother? For example can I float a text field ontop of certain parts of my canvas, disable the border and set the color to the canvas color?

无论如何要“浮动”html元素在彼此之上?例如,我可以在画布的某些部分上浮动一个文本字段,禁用边框并将颜色设置为画布颜色吗?

Thank You

谢谢你

回答by ChrisJ

You may use the CSS position: absoluteproperty with z-index: 1to place elements above the canvas.

您可以使用 CSS position: absolute属性和z-index: 1将元素放置在画布上方。

EDIT: added an example: here the div that contains "1234" floats on top of the div that contains "abcd" (that could be replaced with a canvas element)

编辑:添加了一个例子:这里包含“1234”的div浮动在包含“abcd”的div的顶部(可以用canvas元素替换)

<div id="wrapper">
    <div style="position: absolute; left: 10px; top: 10px; width:200px; height:100px; background-color: yellow;">
        abcd
    </div>
    <div style="position: absolute; z-index: 1; left: 50px; top: 20px; width:100px; height:20px; background-color: green;">
        1234
    </div>
</div>

回答by tomasb

You can use 'somehow' invisible text-control to gain control over the text being input and copy innerHTML on the canvas on keypress. Im doing similar stuff, copying computed font css attributes of the text present in DOM and more. Z-indexes work pretty straight. The setFocus() function can help too.

您可以使用“以某种方式”不可见的文本控件来控制输入的文本并通过按键在画布上复制innerHTML。我在做类似的事情,复制 DOM 中存在的文本的计算字体 css 属性等等。Z 索引的工作非常直接。setFocus() 函数也可以提供帮助。