Skip to content

Instantly share code, notes, and snippets.

@talltyler
Created April 9, 2013 14:01
Show Gist options
  • Save talltyler/5345894 to your computer and use it in GitHub Desktop.
Save talltyler/5345894 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 );
@The0mbudsman
Copy link

The0mbudsman commented Oct 23, 2022

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

I am almost 10 years late, but to anyone in the future, you need to install and import underscore js for this solution

npm i underscore
const _ = require('underscore');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment