如何在画布元素中嵌入输入或文本区域? [英] How to embed an input or textarea in a canvas element?

查看:53
本文介绍了如何在画布元素中嵌入输入或文本区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在HTML画布上显示其中的输入框或文本区域来编辑文本.

I want to edit text on an HTML canvas by displaying an input box or textarea inside it.

但是,当我在输入框中键入任何文本时,并在画布上单击后,将显示输入文本.

However, when I type any text in the input box, and after clicking on the canvas, the input text is getting displayed.

但是我不希望它表现那样.我希望嵌入输入框或文本区域,以便可以直接在canvas元素上编辑文本.

But I don't want it to behave like that. I want the input box or textarea to get embedded so that I can edit text directly on the canvas element.

推荐答案

画布是一个简单的位图,不支持DOM元素(例如输入)的嵌入.

Canvas is a simple bitmap and does not supporting embedding of DOM elements (such as input).

要实现此目的,您需要伪造"输入内容并使用上下文的fillText来在画布上绘制文本.

To accomplish this, you will need to "fake" the input by typing and use the fillText of context to draw in the text on the canvas.

例如,您可以在需要输入时将输入元素放置在画布上.完成后,提取输入值并将其绘制到画布上.

You can for example place the input element on top of canvas when you need some input. When done, extract the value of input and draw it onto canvas.

在画布上单击任意位置:

Click anywhere on the canvas:

点击进入:

var canvas = document.getElementById('myCanvas'),
    ctx = canvas.getContext('2d'),
    font = '14px sans-serif',
    hasInput = false;

canvas.onclick = function(e) {
    if (hasInput) return;
    addInput(e.clientX, e.clientY);
}

//Function to dynamically add an input box: 
function addInput(x, y) {

    var input = document.createElement('input');

    input.type = 'text';
    input.style.position = 'fixed';
    input.style.left = (x - 4) + 'px';
    input.style.top = (y - 4) + 'px';

    input.onkeydown = handleEnter;

    document.body.appendChild(input);

    input.focus();

    hasInput = true;
}

//Key handler for input box:
function handleEnter(e) {
    var keyCode = e.keyCode;
    if (keyCode === 13) {
        drawText(this.value, parseInt(this.style.left, 10), parseInt(this.style.top, 10));
        document.body.removeChild(this);
        hasInput = false;
    }
}

//Draw the text onto canvas:
function drawText(txt, x, y) {
    ctx.textBaseline = 'top';
    ctx.textAlign = 'left';
    ctx.font = font;
    ctx.fillText(txt, x - 4, y - 4);
}

#myCanvas {
    background: lightgrey;
}

<canvas id="myCanvas"></canvas>

设置输入框的样式,使其融合得更好.您可以改用文本区域,依此类推.

Style the input box so it blends better. You can use a textarea instead and so forth.

注意:如果要在以后编辑文本,则需要在内部跟踪文本/位置.

Note: If you want to edit the text at some later point you need to keep track of the text/position internally.

这篇关于如何在画布元素中嵌入输入或文本区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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