带有从右到左字符串的 HTML5 Canvas fillText [英] HTML5 Canvas fillText with Right-to-Left string

查看:30
本文介绍了带有从右到左字符串的 HTML5 Canvas fillText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 HTML5 Canvas 的 2d 上下文中使用 fillText() 方法来绘制用阿拉伯语书写的字符串.它工作得很好,直到我在字符串的末尾放了一个标点符号.然后标点符号出现在字符串的错误一侧(在开头,而不是结尾,好像它是一个 ltr 而不是 rtl 字符串).我使用了 Context.textAlign 属性,但这似乎只关心字符串相对于指定位置的绘制方式,而不是文本的实际方向.有没有人知道解决这个问题的方法?

I am trying to use the fillText() method on an HTML5 Canvas' 2d Context to draw a string written in Arabic. It works perfectly, until I put a punctuation mark at the end of the string. Then the punctuation mark appears on the wrong side of the string (at the beginning, rather than the end, as if it were a ltr not rtl string). I played with the Context.textAlign property, but that seems to concern only the way the string is drawn relative to the specified position, not the actual direction of the text. Does anyone know of a solution to this?

谢谢.

更新: 我找到的答案是向页面上的画布元素添加dir"属性.例如,

Update: The answer I found is to add a "dir" attribute to the canvas element on the page. For example,

<canvas dir="rtl">

但是,我仍然不知道如何更改发送到 fillText 的单个字符串的 dir 属性.有什么想法吗?

However, I still don't know how to change the dir attribute for individual strings sent to fillText. Any ideas?

推荐答案

您不需要为每个单独的字符串设置方向.请参阅以下示例,该示例还显示了正确使用隐式双向控制标记以实现正确显示顺序:

You don't need to set the direction for each individual string. See the following example which also shows the proper use of implicit bidi control marks for proper display order:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

  <body>
    <canvas id="myCanvas" width="700" dir="rtl" height="250" style="border:1px solid #d3d3d3;">
      Your browser does not support the HTML5 canvas tag.
    </canvas>

    <script type="text/javascript" charset="utf-8">
      var c = document.getElementById("myCanvas");
      var cArabic = c.getContext("2d");
      cArabic.font="25px Arial";

      // Simple Sentence with punctuation.
      var str1 = "این یک آزمایش است.";
      // Few sentences with punctuation and numerals. 
      var str2 = "۱ آزمایش. 2 آزمایش، سه آزمایش & Foo آزمایش!";
      // Needs implicit bidi marks to display correctly.
      var str3 = "آزمایش برای Foo Ltd. و Bar Inc. باشد که آزموده شود.";
      // Implicit bidi marks added; "Foo Ltd.&lrm; و Bar Inc.&lrm;"
      var str4 = "آزمایش برای Foo Ltd.‎ و Bar Inc.‎ باشد که آزموده شود.";

      cArabic.fillText(str1, 600, 60);
      cArabic.fillText(str2, 600, 100);
      cArabic.fillText(str3, 600, 140);
      cArabic.fillText(str4, 600, 180);
    </script>

  </body>
</html>

这是输出:26.0.1410.64 m 渲染">

And here is the output:

这篇关于带有从右到左字符串的 HTML5 Canvas fillText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆