Created
April 9, 2013 14:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
}); | |
}; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ctx.letterSpacing = 10; | |
ctx.fillStyle = 'black'; | |
ctx.fillText( 'Hello World!', 10, 10 ); |
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
do you have working example of this code ? I tried to implement this but it doesnt work please advise?