Javascript: create font from blob data

元气小坏坏 提交于 2021-01-28 00:34:30

问题


I'm trying to create an assets loader based on XMLHttpRequest only. I'm loading images with the help of XMLHttpRequest, getting it's responce of "blob" type and converting it to a normal html element. Something like this:

var request = new XMLHttpRequest();
var image;
var blob;
request.onreadystatechange= function() {
    if (request.readyState === 4) {
        if (request.status === 200) {
            blob = request.response;
            image = new Image();
            image.src = window.URL.createObjectURL(blob);
        }
    }
};
request.responseType = 'blob';
request.open("GET", "resource_url", true);
request.send();

I want to implement the same conception for loading fonts and registering them on the page after loaded. It it posible in general? What should I do with blob responce after it is received?


回答1:


For starters you'll need to switch to CSS for this, as that's the only way of loading fonts into a page currently (the Font Loading API is on its way, but has almost zero support right now).

In CSS, custom font declaration looks something like this:

@font-face {
    font-family: "Yo Font";
    src: url(data:application/x-font-woff;charset=utf-8;base64,d09GRgABAA...) format("woff");
    font-weight: normal;
    font-style: normal;
}

How exactly your font-face declaration looks depends on the type of fonts you're loading. More info in the MDN CSS spec for font-face here.

This means that you'll have to create a stylesheet dynamically, using it to load your fonts. You have two methods for updating the stylesheet.

  1. Dynamically updating the rules of the stylesheet via the StyleSheet DOM API (most efficient method), you'd get your StyleSheet object with styleElement.stylesheet
  2. Appending your font-face declarations to the innerHTML of a <style /> element.


来源:https://stackoverflow.com/questions/34922932/javascript-create-font-from-blob-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!