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

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>

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.

Leave a Comment