-
-
Save ddanninger/f9ce4e63e7b01a4df6fb3055d543008f to your computer and use it in GitHub Desktop.
Fabric.js + Opentype.js for pixelperfect valentine cards
This file contains hidden or 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
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