CanvasRenderingContext2D:direction 属性

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Canvas 2D API 的 CanvasRenderingContext2D.direction 属性用来在绘制文本时,描述当前文本方向。

可能的取值:

"ltr"

文字方向为从左到右。

"rtl"

文字方向为从右到左。

"inherit"

文字方向从相应的 <canvas> 元素或 Document 继承。

默认值为 "inherit"

示例

改变文字方向

这个示例绘制了两段文字。第一段是从左到右的,第二段是从右到左的。注意在 ltr 中的“Hi!”变成了在 rtl 中的“!Hi”。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "48px serif";
ctx.fillText("Hi!", 150, 50);
ctx.direction = "rtl";
ctx.fillText("Hi!", 150, 130);

结果

规范

Specification
HTML
# dom-context-2d-direction-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
direction

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见