Skip to content

Instantly share code, notes, and snippets.

@lukasvan3l
Created April 17, 2017 06:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lukasvan3l/9ebfaafc85a2072bd6d4cc35e69cf803 to your computer and use it in GitHub Desktop.
Save lukasvan3l/9ebfaafc85a2072bd6d4cc35e69cf803 to your computer and use it in GitHub Desktop.
Fabric.js + Opentype.js for pixelperfect valentine cards
const canvas = fabric.createCanvasForNode(width, height);
canvas.contextCache.constructor.prototype.getFontSize = function getFontSize() {
return 1 * this.font.split('-')[1];
};
canvas.contextCache.constructor.prototype.getFontFamily = function getFontFamily() {
return this.font.split('-')[0]
};
canvas.contextCache.constructor.prototype.measureText = function measureText(text) {
let width;
const font = fonts[this.getFontFamily()];
font.forEachGlyph(`${text} `, 0, 0, this.getFontSize(), {}, (glyph, x) => {
width = x;
});
return { width };
};
canvas.contextCache.constructor.prototype.fillText = function fillText(text, x, y) {
const width = this.measureText(text).width;
const isRtl = this.direction === 'rtl';
const offsetFactor = {
left: 0,
center: 0.5,
right: 1,
start: isRtl ? 1 : 0,
end: isRtl ? 0 : 1,
};
const font = fonts[this.getFontFamily()];
const offsetX = x - (width * offsetFactor[this.textAlign]);
const path = font.getPath(text, offsetX, y, this.getFontSize());
path.fill = this.fillStyle;
path.draw(this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment