单个文本的 HTML5 Canvas RTL [英] HTML5 Canvas RTL for Individual Texts
问题描述
我有一个 <canvas>
,我想在上面呈现从右到左的字符串(例如,中间有一些英文单词的希伯来语句子).
对于整个画布,可以指定 dir
属性.因此,在我的示例中,我将使用 <canvas dir="rtl/>
.
不幸的是,此解决方案远未完成.我在同一个应用程序中有一些 LTR 句子(例如,只有英语,或者英语中间有一些希伯来语,但不是相反的).
- 有没有办法在不使用两个或多个
es 的情况下为每个字符串指定
dir
?
以下是 dir
属性如何改变 canvas
处理双向字符串的简单示例:
var text = 'קצת text בעברית'var rtlCanvas = document.getElementById('rtl-canvas')var rtlCtx = rtlCanvas.getContext('2d')rtlCtx.font = '24px Arial'rtlCtx.fillText(text, 250, 50)var ltrCanvas = document.getElementById('ltr-canvas')var ltrCtx = ltrCanvas.getContext('2d')ltrCtx.font = '24px Arial'ltrCtx.fillText(text, 0, 50)
<p>dir=rtl 看起来不错:</p><canvas id="rtl-canvas" dir="rtl" width=300 height=100/><div><p>dir=ltr,交换第一个和最后一个词
<canvas id="ltr-canvas" dir="ltr" width=300 height=100/>
您可以根据需要以编程方式更改 dir
属性来控制每个字符串的方向:
var text = 'קצת text בעברית'var canvas = document.getElementById('canvas')var ctx = canvas.getContext('2d')ctx.font = '24px Arial'ctx.fillText(文本, 165, 50)canvas.setAttribute('dir','ltr');ctx.fillText(text, 0, 100)
<div><canvas id="canvas" dir="rtl" width=300 height=300/>
I have a <canvas>
on which I want to render right-to-left strings (e.g. Hebrew sentence with some English words somewhere in the middle).
For the whole canvas, a dir
attribute may be specified. So, in my example I'd use <canvas dir="rtl />
.
Unfortunately, this solution is far from being complete. I have some sentences in the same application that are LTR (for example, English only, or English with some Hebrew at the middle, but not the opposite).
- Is there any way to specify
dir
per string basis, without using two or more<canvas>
es?
Here's a naive example of how the dir
attribute chages that way the canvas
handles bidirectional strings:
var text = 'קצת text בעברית'
var rtlCanvas = document.getElementById('rtl-canvas')
var rtlCtx = rtlCanvas.getContext('2d')
rtlCtx.font = '24px Arial'
rtlCtx.fillText(text, 250, 50)
var ltrCanvas = document.getElementById('ltr-canvas')
var ltrCtx = ltrCanvas.getContext('2d')
ltrCtx.font = '24px Arial'
ltrCtx.fillText(text, 0, 50)
<div>
<p>Looking good with dir=rtl:</p>
<canvas id="rtl-canvas" dir="rtl" width=300 height=100/>
</div>
<div>
<p>With dir=ltr, first and last words are swapped</p>
<canvas id="ltr-canvas" dir="ltr" width=300 height=100/>
</div>
You can control the direction per string by changing the dir
attribute programmatically as needed:
var text = 'קצת text בעברית'
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
ctx.font = '24px Arial'
ctx.fillText(text, 165, 50)
canvas.setAttribute('dir','ltr');
ctx.fillText(text, 0, 100)
<div>
<canvas id="canvas" dir="rtl" width=300 height=300/>
</div>
这篇关于单个文本的 HTML5 Canvas RTL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!