HTML Canvas - direction 屬性



HTML Canvas 的 direction 屬性使用CanvasRenderingContext2D 介面上下文物件可以更改 Canvas 元素內的文字方向。

它可以用於在向畫布新增文字時指定當前文字方向。

可能的輸入值

該屬性可以取的值為:

序號 值與描述
1 ltr

文字方向從左到右。

2 rtl

文字方向從右到左。

3 inherit

繪製文字到 Canvas 元素的方向將根據 canvas 元素規範適當地獲取。

示例 1

以下示例使用預設的“inherit”方向,使用 HTML Canvas 的direction屬性將文字繪製到 Canvas 元素。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "25px Verdana";
      context.fillText('direction-', 150, 50);
      context.direction = 'inherit';
      context.fillText('direction-', 150, 130);
   </script>
</body>
</html>

輸出

以下程式碼在網頁上返回的輸出為:

HTML Canvas Direction Property

示例 2

以下示例使用 CanvasRenderingContext2D 物件的direction屬性,將文字從右到左繪製到畫布上。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "25px Verdana";
      context.fillText('hello world-', 150, 50);
      context.direction = 'rtl';
      context.fillText('hello world-', 150, 130);
   </script>
</body>
</html>

輸出

以上程式碼在網頁上返回的輸出為:

HTML Canvas Direction Property

示例 3

以下示例使用 CanvasRenderingContext2D 物件的direction屬性,將文字從左到右繪製到畫布上。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "25px Verdana";
      context.fillText('-hello world', 150, 50);
      context.direction = 'ltr';
      context.fillText('-hello world', 150, 130);
   </script>
</body>
</html>

輸出

以上程式碼在網頁上返回的輸出為:

HTML Canvas Direction Property
html_canvas_text.htm
廣告
© . All rights reserved.