Reputation: 2476
Here is a JSFiddle. - The larger the string in length the more space is added to the right.
I am trying to create some code that justifies text on canvas:
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();
});
I don't want the words to be justified, instead I would like the letters to be justified.
Basically this iterates over the string's characters and draws them onto the canvas with added spacing between each character to FILL a certain width. This code seems to add too much spacing to the right. The larger the string in character length the more space is added to the right.
I think it may be something to do with the space
variable calculation. I am trying to fit a random length string into a specific space by lengthening the space between each character.
Any help is appreciated!
Upvotes: 0
Views: 582
Reputation:
You are very close but you are only adding width of the space and forget to add the width of the char as well:
Try this and it should work:
xpos += space + ctx.measureText(char).width;
Also for more accuracy you should not round your spacing to integer value. Canvas can handle sub-pixeling and it will give a better result (I modified this in the fiddle as well in canvas to demonstrate).
Upvotes: 1