Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This code gives the HTML canvas element JavaScript support for letter spacing. Don't confuse letter spacing with kerning http://en.wikipedia.org/wiki/Kerning This code is basically from http://stackoverflow.com/a/15509006
(function(){
var _fillText,
__slice = [].slice;
_fillText = CanvasRenderingContext2D.prototype.fillText;
CanvasRenderingContext2D.prototype.fillText = function() {
var args, offset, previousLetter, str, x, y,
_this = this;
str = arguments[0], x = arguments[1], y = arguments[2], args = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
if (this.letterSpacing == null || this.letterSpacing === 0) {
return _fillText.apply(this, arguments);
}
offset = 0;
previousLetter = false;
return _.each(str, function(letter) {
_fillText.apply(_this, [letter, x + offset + _this.letterSpacing, y].concat(args));
offset += _this.measureText(letter).width + _this.letterSpacing;
return previousLetter = letter;
});
};
})();
ctx.letterSpacing = 10;
ctx.fillStyle = 'black';
ctx.fillText( 'Hello World!', 10, 10 );
@thetechie13

This comment has been minimized.

Copy link

commented May 29, 2013

do you have working example of this code ? I tried to implement this but it doesnt work please advise?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.