Javascript:从Blob数据创建字体 [英] Javascript: create font from blob data

查看:99
本文介绍了Javascript:从Blob数据创建字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅基于XMLHttpRequest创建资产加载器.我正在XMLHttpRequest的帮助下加载图像,获得"blob"类型的响应并将其转换为普通的html元素.像这样:

  var request = new XMLHttpRequest();var image;var blob;request.onreadystatechange = function(){如果(request.readyState === 4){如果(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(); 

我想实现相同的概念来加载字体,并在加载后在页面上注册它们.一般情况下可以吗?收到Blob响应后该怎么办?

解决方案

对于初学者,您需要为此切换到CSS,因为这是当前将字体加载到页面中的唯一方法(

font-face 声明的确切外观取决于所加载字体的类型.MDN CSS规范中有关字体在此处的更多信息.

这意味着您必须动态创建样式表,并使用它来加载字体.您有两种更新样式表的方法.

  1. 通过 StyleSheet DOM API动态更新样式表的规则(最有效的方法),您将使用 styleElement.stylesheet
  2. 获得 StyleSheet 对象
  3. font-face 声明附加到< style/> 元素的 innerHTML .

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?

解决方案

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.

这篇关于Javascript:从Blob数据创建字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆