如何在HTML 5 Canvas中添加可选文本?

Sac*_*eph 6 javascript html5 canvas html5-canvas

我需要在画布上放置一个文本标签.可能吗?我怎样才能做到这一点?我知道有fillText但fillText没有给我流畅的输出文本.我还希望标签上的文本可以由用户复制,如果我使用fillText,这是不可能的.

lox*_*xxy 3

假设您只想在 html 页面的画布顶部放置一些文本:

HTML:

<label>Yahoo, I'm on top of canvas??</label>
<canvas width="500" height="500" ></canvas>
Run Code Online (Sandbox Code Playgroud)

CSS:

canvas {
    border:1px solid gray;
}

label {
    position:absolute;
    top:20px;
    left:20px;
}
Run Code Online (Sandbox Code Playgroud)

Working demo


编辑:

根据编辑,如果您正在寻找一种在画布内选择文本的解决方案,那么这会更加痛苦。

我建议使用CreateJS. 使用画布时,它会让您的生活变得更加轻松。

虽然该库没有为您提供可选择的文本,但它更容易实现。

以下是DEMO创建可选文本的方法。

// Text Selector Class
function Selector(stage, text) {
    var select = new createjs.Shape();

    function selector(x, y, width, height) {
        select.graphics.clear().beginFill("#ace")
            .drawRect(x || 0, y || 0, width || 0, height || 0);
    }
    var tuw = text.getMeasuredWidth();
    var tuh = text.getMeasuredHeight();
    text.addEventListener("mousedown", function (e) {
        var startX = e.rawX;
        var onMove = function (e) {
            if (e.rawX >= text.x && e.rawX <= text.x + tuw) selector(startX, text.y, e.rawX - startX, tuh);
        };
        var onUp = function () {
            stage.removeEventListener("stagemousemove", onMove);
            selector();
        };
        stage.addEventListener("stagemousemove", onMove);
        stage.addEventListener("stagemouseup", onUp);
    });
    return select;
}


var stage = new createjs.Stage("shape");

// Text Node
var text = new createjs.Text("Hello World");
text.x = 100;
text.font = "20px Arial";
text.color = "#ff7700";
text.cursor = "text";
stage.addChild(text);

// Attach Selector 
stage.addChildAt(new Selector(stage, text), 0);

// Important
stage.enableMouseOver();
setInterval(function () {
    stage.update();
}, 100);
Run Code Online (Sandbox Code Playgroud)