Skip to content

Instantly share code, notes, and snippets.

@shyiko
Last active December 24, 2016 03:20
Show Gist options
  • Save shyiko/caa8be675e6dafee47c76a004202258d to your computer and use it in GitHub Desktop.
Save shyiko/caa8be675e6dafee47c76a004202258d to your computer and use it in GitHub Desktop.
jsbin :: canvas-text-opentypejs-shim
<!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</title>
</head>
<body>
<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']
/**
* @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)
}
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 = canvas.getContext('2d')
useOpenTypeJsForText(ctx, {
resolveFont: function (o) {
if (splitFontFamily(o.fontFamily)[0] === 'Open Sans') {
return font
}
}
})
ctx.font = '26px "Open Sans"'
ctx.fillText('Hello World', 0, 26)
})
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment