如何使用 Javascript 将图标字体渲染为图片

前言

在软件开发中肯定要用到图标,比如下图的 Groove 音乐中就用到了许多图标。一种获取这些图标的方法是把 Groove 音乐截个图,然后熟练地开启 Photoshop,开始抠图。这种方式很逊,效率也很低(虽然我刚开始就是这么干的)。

如何使用 Javascript 将图标字体渲染为图片

如果打开 C:/Program Files/WindowsApps(需要修改权限才能进入),可以发现几个名字里带 ZuneMusic 的文件夹,其中的某一个文件夹中会有字体文件 SegMVR2.ttf。这是一个图标字体文件,双击安装之后,打开 Windows 自带的字符映射表应用,将字体换为 Segoe MVR MDL2 Assets,可以看到里面的字符其实就是图标。其实可以用 Metro Studio 将这些字体导出为 png、svg 等格式的图片,但是 Metro Studio 导出的字符看起来很细,也无法分别控制上下和左右的内边距,所以这里改用 Javascript 操作 canvas 绘制图标,然后导出为 png。

如何使用 Javascript 将图标字体渲染为图片

实现方式

在 CodePen 上已经有人给出了将 Microsoft 开源的 Fabric UI Icon 渲染为 png 图片的 demo,效果很不错。阅读源代码之后可以发现,他在 getFontIconCharacter() 先创建了一个临时的元素,根据想要的图标的名字设置元素的 className,获取 ::before伪元素的 content 中字符的 Unicode,接着在 drawIcon() 中使用 context.fillText() 方法绘制字符,最后 canvas.toDataURL() 就能将 canvas 的内容转换为 base64 格式的图片。

可以看到,对于自定义的的字体,我们只需知道字符的 Unicode,就能实现导出功能。

html

html 和 coepen 中的几乎完全一样,唯一不同的地方就是将 font-class 换成了 font-unicode,因为我们只有字符的 unicode。


    iconfont to png

        Render Office Fabric UI Icons into Canvas
        This is a simple tool to render an icon from the Office Fabric UI icon font into an
            HTML <canvas> with a background color. Right-click and save the image to use it.

                Icon/Canvas Specifications

                                Icon unicode

                                Font size (px)

                                Image width (px)

                                Image height (px)

                                Left offset

                                Top offset

                                Background color

                                Icon color

                                 Use a circle as the
                                    background fill

                    If the icon does not render immediately, wait a few seconds and press the Render button
                        again; the webfont may still be loading.

                Result

                 Download the image
                Data URL

css

与 codepen 中的代码相比,这里只是多了一个 @font-face 声明要使用的字体。图标的下载地址在 蓝奏云,密码为 abcr

@import url(https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/11.0.0/css/fabric.min.css);

@font-face {
    font-family: 'Segoe MVR MDL2 Assets';
    src: url('SegoeMVRMDL2Assets.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

html {
    box-sizing: border-box;
}

*,
*:before,
*:after {
    box-sizing: inherit;
}

body {
    font-family: "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif;
    background-color: #0078d4;
    color: white;
}

.ms-Grid {
    margin: 0 auto;
    padding: 0 16px;
    max-width: 1280px;
}

.ms-Grid-row {
    margin-left: -16px;
    margin-right: -16px;
}

.ms-Grid-col {
    padding: 0 16px;
}

label {
    display: block;
    margin-bottom: 0.5em;
}

input {
    border: none;
    display: block;
    margin-bottom: 2em;
    padding: 5px;
    width: 100%;
    font-size: 16px;
}

input[type="checkbox"] {
    display: inline-block;
    padding: 0;
    width: auto;
}

input[type="button"],
input[type="submit"],
.ms-button {
    cursor: pointer;
    display: inline-block;
    padding: 0.75em 2em;
    text-decoration: none;
    width: auto;

}

.ms-button .ms-Icon {
    transform: translateY(2px);
}

.canvas-container {
    background-color: white;
    display: inline-block;
    margin-bottom: 1em;
    padding: 10px;
    width: auto;
}

#canvas {
    color: black;
    font-family: FabricMDL2Icons;
}

js

这里我们主要修改了 getFontIconCharacter() 函数,直接根据输入框的内容返回字符的 Unicode。

const form = document.getElementById("form");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const download = document.getElementById("download-link");
const dataURL = document.getElementById("dataURL");
const fontFamily = "Segoe MVR MDL2 Assets";

function getFontIconCharacter(unicode) {
    return String.fromCharCode(parseInt(unicode, 16));
}

function drawCircle() {
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    var radius = canvas.width / 2;
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = document.getElementById("bg-color").value || "#777777";
    context.fill();
}

function drawRect() {
    context.fillStyle = document.getElementById("bg-color").value || "#777777";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

function drawIcon() {
    canvas.width = parseInt(document.getElementById("image-width").value, 10) || 92;
    canvas.height = parseInt(document.getElementById("image-height").value, 10) || 92;
    context.clearRect(0, 0, canvas.width, canvas.height);
    if (document.getElementById("shape").checked) {
        drawCircle();
    } else {
        drawRect();
    }
    context.fillStyle = document.getElementById("icon-color").value || "#FFFFFF";
    let fontUnicode = document.getElementById("font-unicode").value,
        fontSize = document.getElementById("font-size").value || 280,
        topOffset = document.getElementById("top-offset").value || 210,
        leftOffset = document.getElementById("left-offset").value || 210;
    context.font = ${fontSize}px ${fontFamily};
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(getFontIconCharacter(fontUnicode), parseInt(leftOffset, 10), parseInt(topOffset, 10));
    dataURL.value = canvas.toDataURL();

}

window.addEventListener('load', function () {
    drawIcon();
});

document.addEventListener('DOMContentLoaded', function () {
    context.font = "10px " + fontFamily;
    context.fillText("...", 0, 0);
});

form.addEventListener("submit", function (event) {
    event.preventDefault();
    drawIcon();
});

download.addEventListener("click", function (event) {
    if (typeof this.download !== "undefined") {
        this.href = canvas.toDataURL();
        this.download = ${document.getElementById("font-unicode").value}.png;
    } else {
        event.preventDefault();
        alert("Your browser does not support downloading a canvas image. Please right-click on the image to save it.");
    }
});

dataURL.addEventListener("focus", function (event) {
    dataURL.select();
});

效果

打开 html 之后如下图所示,只需修改 Icon unicode,再点击 Render Font Icon 按钮,就能在右侧的画布中看到图标,点击 Download the image 按钮就能下载图标了。

如何使用 Javascript 将图标字体渲染为图片

Original: https://www.cnblogs.com/zhiyiYo/p/16257021.html
Author: 之一Yo
Title: 如何使用 Javascript 将图标字体渲染为图片

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/582826/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 列表初始化

    C++11将列表初始化(大括号初始化)作为一种通用的初始化方式.可用于所有类型. 数组以前就可以用列表初始化,但 C++11 中的列表初始化新增了一些功能: 初始化数组时,可省略等…

    Linux 2023年6月13日
    078
  • Docker Compose 安装

    方法一:这种方式相对简单,但是由于网络问题,常常安装不上,并且经常会断开,可以尝试使用网络上提供的国内安装的方法将@version 替换为要安装的版本号 sudo curl -L …

    Linux 2023年6月13日
    098
  • 小白上手Linux系统安装Tomcat教程

    1.准备阶段: 要有JDK环境,在安装好JDK后再配置tomcat,JDK安装详情在我博客中可以看到。 3.导入 进入到Xshell输入在自己的文件中(cd /home/lzh)好…

    Linux 2023年6月13日
    0107
  • Redis缓存穿透、缓存击穿、缓存雪崩

    Redis缓存穿透、缓存击穿缓存雪崩 redis常被用于作为后台数据库的缓存,缓存一些热点访问数据,根据局部性原理,缓存能够处理大部分请求。当请求数据未命中缓存时,才会引起对数据库…

    Linux 2023年6月13日
    0106
  • 使用kubectl管理Kubernetes(k8s)集群:常用命令,查看负载,命名空间namespace管理

    服务器版本 docker软件版本 CPU架构 CentOS Linux release 7.4.1708 (Core) Docker version 20.10.12 x86_64…

    Linux 2023年6月7日
    0163
  • CH343芯片应用—硬件设计

    CH343属于沁恒第三代USB转串口芯片系列的单串口型号,基于经典版CH340芯片完成技术革新,实现USB转高速异步串口,支持最高6Mbps串口波特率。 电源设计 CH343芯片有…

    Linux 2023年6月7日
    0169
  • protobuf 的交叉编译使用(C++)

    为了提高通信效率,可以采用 protobuf 替代 XML 和 Json 数据交互格式,protobuf 相对来说数据量小,在进程间通信或者设备之间通信能够提高通信速率。下面介绍 …

    Linux 2023年6月7日
    0142
  • Redis源码学习

    为什么要阅读Redis源码? 主要原因就是『简洁』。如果你用源码编译过Redis,你会发现十分轻快,一步到位。其他语言的开发者可能不会了解这种痛,作为C/C++程序员,如果你源码编…

    Linux 2023年5月28日
    094
  • 辗转相除法:(求最大公约数)

    辗转相除法:(最大公约数)又名欧几里德算法(Euclidean algorithm),是求最大公约数的一种方法。它的具体做法是:用较大数除以较小数,再用出现的余数(第一余数)去除除…

    Linux 2023年6月7日
    0117
  • 关于阿里云ECS Centos 5/6/7 Linux Glibc库严重安全漏洞修复方法

    本文来自转载http://www.shidehui.com/jingyan/about-ali-cloud-ecs-centos-567-linux-glibc-library-s…

    Linux 2023年6月13日
    0127
  • Java秒杀系统二:Service层

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Linux 2023年6月11日
    0103
  • win10安装redis

    下载地址:https://github.com/MicrosoftArchive/redis/releases 这个太慢了 https://github.com/ServiceSt…

    Linux 2023年5月28日
    0124
  • 基于 vite 创建 vue3 全家桶项目(vite + vue3 + tsx + pinia)

    vite 最近非常火,它是 vue 作者尤大神发布前端构建工具,底层基于 Rollup,无论是启动速度还是热加载速度都非常快。vite 随 vue3 正式版一起发布,刚开始的时候与…

    Linux 2023年6月7日
    0105
  • Centos8 设置中文

    1、一般情况 1.1 进入设置选择 Region&Language 1.2 点击 加号 1.3 点击 汉语(中国) 1.4 选择 汉语(智能拼音) 2、特殊情况 有些虚拟机…

    Linux 2023年5月27日
    0123
  • Redis 全局通用命令整理

    转载请注明出处: 1.查看所有键 该命令会存在线程阻塞问题,keys 命令也可以通过正则匹配获取存在的缓存数据 Redis从2.8版本后,提供了一个新的命令scan,它能有效的解决…

    Linux 2023年5月28日
    096
  • python学习(解析python官网会议安排)

    对html的解析是网页抓取的基础,分析抓取的结果找到自己想要的内容或标签以达到抓取的目的。 HTMLParser是python用来解析html的模块。它可以分析出html里面的标签…

    Linux 2023年6月14日
    0108
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球