×

HTML5 Canvas的文本如何实现垂直对齐

作者:Terry2016.11.12来源:Web前端之家浏览:20322评论:0

垂直对齐,使用CSS很容易实现,如果想在HTML5 Canvas中实现垂直对齐,如何设置呢,这就是今天要分享的笔记。

61.png

HTML画布垂直对齐的文本,我们可以使用的textBaseline在画布范围内的属性值。textBaseline可以设置以下值之一 :top, hanging, middle, alphabetic, ideographic, and bottom。除非另有规定,textBaseline属性默认为字母。

context.textBaseline=[value];
<!DOCTYPE HTML> 
<html> 
<head> 
<title>html5_canvas_text_baseline</title>
<style> 
body {margin: 0px;padding: 0px;}
#myCanvas {border: 1px solid #9C9898; margin:0 auto;margin-top:200px; margin-left:100px;}
</style> 
<script> 
window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
 
    var x = canvas.width / 2;
    var y = canvas.height / 2;
    context.font = "30pt Calibri";
    // textAlign aligns text horizontally relative to placement
    context.textAlign = "center";
    // textBaseline aligns text vertically relative to font style
    context.textBaseline = "middle";
    context.fillStyle = "blue";
    context.fillText("Hello World!", x, y);
};
</script> 
</head> 
<body> 
 <canvas id="myCanvas" width="578" height="200"> 
 </canvas> 
</body> 
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/qianduan1477670400626.html

网友评论文明上网理性发言 已有0人参与

发表评论: