0

My page has a Canvas that i want to add some text to it.

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"></canvas>

<script>

var txt1 = 'فارسی';
var txt2 = '۴۷';
  
var myText = txt1 + txt2;
//var myText = txt2 + txt1;


var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
ctx.width = 400;
ctx.height = 400;
ctx.fillStyle = "#777";
ctx.fillRect(0,0,400,400);
ctx.font = "normal 50px tahoma";
ctx.fillStyle = "#FFF";
ctx.direction = "rtl";
ctx.fillText(myText,70,110);

</script>

</body>
</html>

i set ctx.direction = "rtl"; before ctx.fillText !

in IE and Firefox:

Text direction is not correct, The Number is placed at the end of string anyway!

myText = txt1 + txt2; is same as myText = txt2 + txt1;

How to resolve it?

Paebbels
  • 15,573
  • 13
  • 70
  • 139

1 Answers1

0

Yes, ctx.direction is currently only supported in chrome and Safari : https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/direction#Browser_compatibility

A solution to control the rendering order of your two strings would be to draw one the the two part on a buffer canvas, and then draw this buffer canvas at the end of your first rendered text.

var txt = ['فارسی','۴۷'];

var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
c.width = 400;
c.height = 400;
ctx.fillStyle = "#777";
ctx.fillRect(0,0,400,400);
// our buffer canvas
var can = c.cloneNode(true);
var ctx2 = can.getContext('2d');

ctx.font = "normal 50px tahoma";
ctx.fillStyle = "#FFF";

ctx2.font = ctx.font
ctx2.fillStyle = ctx.fillStyle;

ctx2.fillText(txt[1], 0,110);
// get the width of the first text
var textWidth = ctx.measureText(txt[0]).width;
ctx.fillText(txt[0],70,110);
// draw our buffer canvas at the end of the text
ctx.drawImage(can, 70+textWidth, 0);

// clear the buffer
ctx2.clearRect(0,0,c.width,c.height);

// inverse the order of the text
ctx2.fillText(txt[0], 0,210);
// get the width of the first text
var textWidth = ctx.measureText(txt[1]).width;
ctx.fillText(txt[1],70,210);
// draw our buffer canvas at the end of the text
ctx.drawImage(can, 70+textWidth, 0);
<canvas id="myCanvas"></canvas>
Kaiido
  • 123,334
  • 13
  • 219
  • 285