The CanvasRenderingContext2D
.textBaseline
property of the Canvas 2D API specifies the current text baseline being used when drawing text.
Syntax
ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
Options
Possible values:
- top
- The text baseline is the top of the em square.
- hanging
- The text baseline is the hanging baseline.
- middle
- The text baseline is the middle of the em square.
- alphabetic
- The text baseline is the normal alphabetic baseline.
- ideographic
- The text baseline is the ideographic baseline; this is the bottom of the body of the characters, if the main body of characters protrudes beneath the alphabetic baseline.
- bottom
- The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders.
The default value is alphabetic
.
Examples
Using the textBaseline
property
This is just a simple code snippet using the textBaseline
property to set a different text baseline setting.
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.font = "48px serif"; ctx.textBaseline = "hanging"; ctx.strokeText("Hello world", 0, 100);
Edit the code below and see your changes update live in the canvas:
Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.font = "48px serif"; ctx.textBaseline = "hanging"; ctx.strokeText("Hello world", 0, 100);</textarea>
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas);
Specifications
Specification | Status | Comment |
---|---|---|
WHATWG HTML Living Standard The definition of 'CanvasRenderingContext2D.textBaseline' in that specification. |
Living Standard |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | 3.5 (1.9.1) | 9 | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 1.0 (1.9.1) | (Yes) | (Yes) | (Yes) |
See also
- The interface defining it,
CanvasRenderingContext2D
.