CanvasRenderingContext2D extensions for better font support
Aim here is to implement CSS 1 and CSS 2 support for fonts;
CSS 1 properties are covered by the context.font property.
CSS 2 properties:
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
text-align
line-height
will be added to the CanvasRenderingContext2D as an extension.
This is a demo.
HTML
<canvas id="c" width="300" height="300"></canvas>
CSS
/* show the boundaries of canvas elements */
canvas { border: 1px dotted #525252; }
JavaScript
(function() {
var slice = Array.prototype.slice,
split = String.prototype.split,
trim = String.prototype.trim,
forEach = Array.prototype.forEach,
reverse = Array.prototype.reverse,
join = Array.prototype.join,
replace = String.prototype.replace,
toUpperCase = String.prototype.toUpperCase,
toLowerCase = String.prototype.toLowerCase,
// String.prototype.camelCase (i.e., this == the string)
camelCase = function() {
return replace.call(this, /-([a-z])/gi, function(s, c) {
return toUpperCase.call(c);
});
};
//
// CSS Helper object
var CSS = {
// @see: https://gist.github.com/1119577
parse: function() {
var styles = slice.call(arguments),
css = {};
forEach.call(styles, function(style) {
var properties = split.call(style, ';');
forEach.call(properties, function(property) {
try {
var pair = split.call(property, ':');
css[camelCase.call(trim.call(pair[0]))] = trim.call(pair[1]);
} catch (propertyError) {
// Hello error
}
});
});
return css;
},
textTransform: {
uppercase: function (text) {
return toUpperCase.call(text);
},
lowercase: function (text) {
return toLowerCase.call(text);
},
capitalize: function (text) {
return camelCase.call(text);
}
},
textAlign: {
// the reason why we have this is because, we draw from right-bound for text-align: right
right: function (text) {
return join.call(reverse.call(split.call(text, '')), '');
}
}
};
...