0

これが JSFiddle です。- 文字列の長さが大きいほど、右側にスペースが追加されます。

キャンバス上のテキストを正当化するコードを作成しようとしています:

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変数計算と関係があるのではないかと思います。各文字間のスペースを長くして、ランダムな長さの文字列を特定のスペースに収めようとしています。

どんな助けでも大歓迎です!

4

1 に答える 1