我正在使用该元素,发现当我将文本放在 Canvas 上时,它太低了。
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.textBaseline = 'top';
context.font = 'normal 50px Arial';
context.fillText("1AFG", 0, 0);
};
imageObj.src = 'http://planttagmaker.herobo.com/images/tag_templates/hibiscus_template.png';
文本放置在 Canvas 顶部下方 10-20 像素处。有人可以解释为什么吗?我确信我可能误解了基线。本质上我希望文本位于 Canvas 的顶部。 X 和 Y 坐标是动态的,因此仅从 y 坐标中减去 10 或 20 px 并不是一个可行的解决方案。
再次感谢您的宝贵时间, 托德
最佳答案
我成功地将字体大小(以像素为单位)转换为点,这给出了文本的像素高度( http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/ )。然后我使用该值作为 y 位置,将 textBaseline 保持为默认字母顺序。
这是代码:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function () {
var fontSize = 50;
context.drawImage(imageObj, 0, 0);
context.font = 'normal ' + fontSize + 'px Arial';
context.fillText("1AFG", 0, pixelsToPoints(fontSize));
};
imageObj.src = 'http://planttagmaker.herobo.com/images/tag_templates/hibiscus_template.png';
function pixelsToPoints(pixels) {
return pixels * 72 / 96;
}
您可以在 http://jsfiddle.net/5Mxez/ 查看示例,它应该在您缩放字体大小时起作用。
关于jquery - html5 Canvas 放置文本太低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14928116/