Chrome OffscreenCanvas自定义字体 [英] Chrome OffscreenCanvas custom fonts
本文介绍了Chrome OffscreenCanvas自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是Chrome 69中发布的新版OffscreenCanvas,似乎无法呈现自定义加载的字体,这些字体可以很好地呈现给普通画布。
I am using the new OffscreenCanvas released in Chrome 69 and cannot seem to render custom loaded fonts that render to ordinary canvases just fine.
是否有获取技巧?
推荐答案
您应该能够使用 FontFace 和 FontFaceSet 接口的从Worker内获取CSS字体加载API 。
You should be able to use the FontFace and FontFaceSet interfaces of the CSS Font Loading API from within a Worker.
主要区别是通过 document.fonts
访问时,FontFaceSet被直接存储为 self.fonts
。
The main difference is that instead of accessing through document.fonts
, the FontFaceSet is stored as self.fonts
directly.
const worker = new Worker(generateURL(worker_script));
worker.onmessage = e => {
const img = e.data;
if(typeof img === 'string') {
console.error(img);
}
else
renderer.getContext('2d').drawImage(img, 0,0);
};
function generateURL(el) {
const blob = new Blob([el.textContent]);
return URL.createObjectURL(blob);
}
<script type="worker-script" id="worker_script">
if(self.FontFace) {
// first declare our font-face
const fontFace = new FontFace(
'Shadows Into Light',
"local('Shadows Into Light'), local('ShadowsIntoLight'), url(https://fonts.gstatic.com/s/shadowsintolight/v7/UqyNK9UOIntux_czAvDQx_ZcHqZXBNQzdcD55TecYQ.woff2) format('woff2')"
);
// add it to the list of fonts our worker supports
self.fonts.add(fontFace);
// load the font
fontFace.load()
.then(()=> {
// font loaded
if(!self.OffscreenCanvas) {
postMessage("Your browser doesn't support OffscreeenCanvas yet");
return;
}
const canvas = new OffscreenCanvas(300, 150);
const ctx = canvas.getContext('2d');
if(!ctx) {
postMessage("Your browser doesn't support the 2d context yet...");
return;
}
ctx.font = '50px "Shadows Into Light"';
ctx.fillText('Hello world', 10, 50);
const img = canvas.transferToImageBitmap();
self.postMessage(img, [img]);
});
} else {
postMessage("Your browser doesn't support the FontFace API from WebWorkers yet");
}
</script>
<canvas id="renderer"></canvas>
这篇关于Chrome OffscreenCanvas自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文