CanvasRenderingContext2D.direction属性 | Canvas CanvasRenderingContext2D

返回到:Canvas API:CanvasRenderingContext2D

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

语法

ctx.direction = "ltr" || "rtl" || "inherit";

选项

有效值:

ltr

文本方向从左向右。

rtl

文本方向从右向左。

inherit

根据情况继承 <canvas> 元素或者 Document

默认值是 inherit

示例

使用direction 属性

这是一段简单的代码片段,对文本设置不同的 direction 数值。

HTML

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

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

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

看下DEMO:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CanvasRenderingContext2D.direction | 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"></canvas>

<canvas id="canvas" width="550" height="500"></canvas>

        
        
            <script>
                var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

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

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

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

            </script>
        
    </body>
</html>

返回到:Canvas API:CanvasRenderingContext2D

作者:terry,如若转载,请注明出处:https://www.web176.com/canvas_api/7962.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年1月6日
下一篇 2023年1月6日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注