返回到:Canvas API:CanvasRenderingContext2D
CanvasRenderingContext2D.textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。
语法
ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
选项
有效值:
top
文本基线在文本块的顶部。
hanging
文本基线是悬挂基线。
middle
文本基线在文本块的中间。
alphabetic
文本基线是标准的字母基线。
ideographic
文字基线是表意字基线;如果字符本身超出了 alphabetic 基线,那么 ideograhpic 基线位置在字符本身的底部。
bottom
文本基线在文本块的底部。与 ideographic 基线的区别在于 ideographic 基线不需要考虑下行字母。
默认值是 alphabetic。
示例
使用 textBaseline 属性
这是一段简单的代码片段,使用 textBaseline 属性设置不同的文本基线。
HTML
<canvas id="canvas" width="550" height="500"></canvas>JavaScript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
ctx.font = '36px serif';
ctx.strokeStyle = 'red';
baselines.forEach(function (baseline, index) {
ctx.textBaseline = baseline;
let y = 75 + index * 75;
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(550, y + 0.5);
ctx.stroke();
ctx.fillText('Abcdefghijklmnop (' + baseline + ')', 0, y);
});
看下DEMO:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CanvasRenderingContext2D.textBaseline | Web176教程www.web176.com</title>
<meta name="robots" content="noindex, nofollow">
<style>
body {
padding: 0;
margin: 0;
}
svg:not(:root) {
display: block;
}
.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}
.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}
.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}
</style>
</head>
<body>
<canvas id="canvas" width="550" height="500"></canvas>
<canvas id="canvas" width="550" height="500"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
ctx.font = '36px serif';
ctx.strokeStyle = 'red';
baselines.forEach(function (baseline, index) {
ctx.textBaseline = baseline;
let y = 75 + index * 75;
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(550, y + 0.5);
ctx.stroke();
ctx.fillText('Abcdefghijklmnop (' + baseline + ')', 0, y);
});
ctx.font = '36px serif';
ctx.strokeStyle = 'red';
baselines.forEach(function (baseline, index) {
ctx.textBaseline = baseline;
let y = 75 + index * 75;
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(550, y + 0.5);
ctx.stroke();
ctx.fillText('Abcdefghijklmnop (' + baseline + ')', 0, y);
});
</script>
</body>
</html>返回到:Canvas API:CanvasRenderingContext2D
作者:terry,如若转载,请注明出处:https://www.web176.com/canvas_api/7958.html
支付宝
微信