我试图在画布上编辑文本 [英] I am trying to edit text on canvas

查看:248
本文介绍了我试图在画布上编辑文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在画布上显示任何输入框或文本区域来编辑文本。
我试过它,我得到的是当我们在输入框中输入任何文本,然后单击画布输入中的文本正在显示。
但我不想这样。我想要输入bor或textarea嵌入在画布上,以便我们可以在画布上直接编辑文本。
请我。

I want to edit text on canvas by displaying any input box or textarea into it. I have tried it and what I am getting is when we type any text in input box and after clicking on canvas the text in input is getting displayed. But I dont want like that. I want that input bor or textarea to get embedded on canvas so that we can edit text durectly on canvas. Please me.

推荐答案

你不能。 Canvas是一个简单的位图,不支持嵌入DOM元素(例如输入)。

You can't. Canvas is a simple bitmap and do not supporting embedding of DOM elements (such as input).

你需要通过输入并使用<

You'll need to "fake" the input by typing and use the fillText of context to draw in the text on the canvas.

您可以例如将输入元素放在画布的顶部,以便在画布上绘制文本。code> fillText 画布时你需要一些输入。完成后,提取输入值并将其绘制到画布上。

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.

这是一个 在线示例

Here is an online example.

点击画布上的任意位置:

Click anywhere 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;
}

输入框的键处理程序:

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;
    }
}

在画布上绘制文字:

function drawText(txt, x, y) {
    ctx.textBaseline = 'top';
    ctx.textAlign = 'left';
    ctx.font = font;
    ctx.fillText(txt, x - 4, y - 4);
}

设置输入框的样式,您可以改用textarea等等。

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天全站免登陆