Skip to content

Instantly share code, notes, and snippets.

@shyiko
Last active December 24, 2016 03:21
Show Gist options
  • Save shyiko/82369ed3ec7ab0edfb8006da69b3b93a to your computer and use it in GitHub Desktop.
Save shyiko/82369ed3ec7ab0edfb8006da69b3b93a to your computer and use it in GitHub Desktop.
jsbin :: canvas-text-opentypejs-shim :: fabric
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas-text-opentypejs-shim :: fabric</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.6/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/opentype.js/0.6.6/opentype.min.js"></script>
<script src="https://rawgit.com/shyiko/canvas-text-opentypejs-shim/master/canvas-text-opentypejs-shim.js"></script>
<script>
(function () {
var useOpenTypeJsForText = window['canvas-text-opentypejs-shim']
// this is here for test purposes only
fabric.devicePixelRatio = 1
// this way fabric tends to yield more consistent results when compared to
// CanvasRenderingContext2D.drawText
fabric.Text.prototype._fontSizeMult = 1.25
/**
* @param fontFamily e.g. "'Open Sans', sans-serif"
* @return e.g. ["Open Sans", "sans-serif"]
*/
function splitFontFamily (fontFamily) {
return fontFamily.split(',')
.map((f) => f.trim().replace(/^['"]/, '').replace(/['"]$/, ''))
.filter(Boolean)
}
// making sure whatever context is used to measure/draw text it has shim active
// (given openTypeJsShimConfig was provided)
fabric.Text.prototype._setTextStyles = (function (original) {
return function (ctx) {
var cfg = this.openTypeJsShimConfig
if (cfg && !ctx.measureText.__openTypeJsShimConfig) {
useOpenTypeJsForText(ctx, cfg)
ctx.measureText.__openTypeJsShimConfig = cfg
}
return original.call(this, ctx)
}
})(fabric.Text.prototype._setTextStyles)
opentype.load(
'https://rawgit.com/google/fonts/master/apache/opensans/OpenSans-Regular.ttf',
function (err, font) {
if (err) {
document.body.appendChild(document.createTextNode(err.stack))
return
}
var canvas = document.createElement('canvas')
canvas.width = canvas.height = 200
document.body.appendChild(canvas)
var ctx = new fabric.Canvas(canvas)
var shimConfig = {
resolveFont: function (o) {
if (splitFontFamily(o.fontFamily)[0] === 'Open Sans') {
return font
}
}
}
ctx.add(new fabric.Text('Hello World', {
left: 0, top: 0, fontFamily: 'Open Sans', fontSize: 26,
openTypeJsShimConfig: shimConfig
}))
})
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment