2013-09-21 65 views
0

Here is a JSFiddle. - 長度越長,向右側添加的空間越多。Justifing letters html5 canvas - Js小提琴示例

我試圖創造一些代碼,在畫布上證明文字:

var ctx = this.ctx; // Is now canvas context 

var str = 'A random string'; 

var width = 500; // The size that the string should fit to 

var strWidth = this.ctx.measureText(str); // The width in pixels of the string when it's put on canvas 

var chars = str.split(''); // Make an array of string 

var space = (width - strWidth.width)/(chars.length - 1); 

var xpos = 1; // Start of text X position 

this.ctx.clearRect(0,0,750,750); 

    var ctx = this.ctx; 

Array.each(chars, function(char) { 
    ctx.fillText(char, xpos, 1); 
    xpos += space.toInt();   
}); 

我不希望是合理的話做的,而不是我想的字母是有道理的。

基本上這個遍歷字符串的字符並將它們繪製到畫布上,每個字符之間增加一個間距以填充一定的寬度。這段代碼似乎在右側添加了太多的空格。字符長度中的字符串越大,則向右側添加的空間越多。

我認爲這可能與space變量計算有關。我試圖通過延長每個字符之間的空間來將隨機長度的字符串放入特定的空間。

任何幫助表示讚賞!

回答

2

你很接近,但你只添加空間的寬度和忘記添加字符的寬度,以及:

試試這個,它應該工作:

xpos += space + ctx.measureText(char).width; 

MODIFIED FIDDLE HERE

同樣爲了更加準確,您不應該將您的間距舍入爲整數值。畫布可以處理子像素,它會給出更好的結果(我在小提琴和帆布中修改了這個以示範)。

+0

絕對太棒了!謝謝。我會在應用中提及你。 – beingalex