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
796 views
in Technique[技术] by (71.8m points)

javascript - How to embed an input or textarea in a canvas element?

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.

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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:

Entering text

Hit enter:

Result on 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>

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

...