Skip to content

Instantly share code, notes, and snippets.

@rowild
Forked from talltyler/gist:5345894
Created February 24, 2016 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rowild/3d6072d02287125d7ade to your computer and use it in GitHub Desktop.
Save rowild/3d6072d02287125d7ade to your computer and use it in GitHub Desktop.
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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment