Skip to content

Instantly share code, notes, and snippets.

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 hongymagic/1108669 to your computer and use it in GitHub Desktop.
Save hongymagic/1108669 to your computer and use it in GitHub Desktop.
CanvasRenderingContext2D fillText with letter-spacing support
/**
* CanvasRenderingContext2D.renderText extension
*/
if (CanvasRenderingContext2D && !CanvasRenderingContext2D.renderText) {
// @param letterSpacing {float} CSS letter-spacing property
CanvasRenderingContext2D.prototype.renderText = function (text, x, y, letterSpacing) {
if (!text || typeof text !== 'string' || text.length === 0) {
return;
}
if (typeof letterSpacing === 'undefined') {
letterSpacing = 0;
}
// letterSpacing of 0 means normal letter-spacing
var characters = String.prototype.split.call(text, ''),
index = 0,
current,
currentPosition = x,
align = 1;
if (this.textAlign === 'right') {
characters = characters.reverse();
align = -1;
} else if (this.textAlign === 'center') {
var totalWidth = 0;
for (var i = 0; i < characters.length; i++) {
totalWidth += (this.measureText(characters[i]).width + letterSpacing);
}
currentPosition = x - (totalWidth / 2);
}
while (index < text.length) {
current = characters[index++];
this.fillText(current, currentPosition, y);
currentPosition += (align * (this.measureText(current).width + letterSpacing));
}
}
}
@mariusteo
Copy link

Context should change textAlign to "left" before rendering and revert to the original one afterword. If you leave it centered the letter will be centered to the calculated position and not start there. Issues will arise when writing complex text

var originlTextAlign=this.textAlign;
        this.textAlign="left"
        while (index < text.length) {
            current = characters[index++];
            this.fillText(current, currentPosition, y);
            currentPosition += (align * (this.measureText(current).width + letterSpacing));
        }
        this.textAlign=originlTextAlign;

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