<分区>
我需要在 Canvas 上放置一个文本标签。可能吗?我怎样才能做到这一点? 我知道有 fillText 但 fillText 没有给我平滑的输出文本。我还希望用户可以复制标签上的文本,如果我使用 fillText,这是不可能的。
<分区>
我需要在 Canvas 上放置一个文本标签。可能吗?我怎样才能做到这一点? 我知道有 fillText 但 fillText 没有给我平滑的输出文本。我还希望用户可以复制标签上的文本,如果我使用 fillText,这是不可能的。
最佳答案
假设,您只是想在 html 页面的 Canvas 顶部放置一些文本:
HTML:
<label>Yahoo, I'm on top of canvas??</label>
<canvas width="500" height="500" ></canvas>
CSS:
canvas {
border:1px solid gray;
}
label {
position:absolute;
top:20px;
left:20px;
}
根据编辑,如果您正在寻找一种在 Canvas 内选择文本的解决方案,那将更加痛苦。
我建议使用 CreateJS 。使用 Canvas 会让您的生活变得更加轻松。
虽然该库没有为您提供可选择的文本,但它更容易实现。
这是一个 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);
关于javascript - 如何在 HTML 5 Canvas 中添加可选文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17922274/