javascript 如何在HTML5画布上绘制Font Awesome双色调图标?

3htmauhk  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(162)

我正尝试在HTML 5画布上绘制字体超赞的双色调图标,但不知道如何获得图标的双色调版本,并正确地着色。例如,this answer中的这段代码将绘制图标的纯色版本:

ctx.font='30px FontAwesome';
ctx.fillText('\uF047',20,50);

但是我不知道如何修改这段代码来绘制双色调图标的每一部分。

y53ybaqx

y53ybaqx1#

FontAwesome DuoTone的工作原理是对::before::after伪元素进行不同的样式设置,而这两个元素都有自己的字形来呈现图标的一部分。
要在<canvas>上获得相同的效果,首先需要将上下文的font属性设置为正确的双色调字体系列(例如'Font Awesome 6 DuoTone'),以便可以访问每个图标的"分隔字形"。
然后,您必须在绘制每个部分之前根据需要设置它们的样式。
下面你会找到一个简单的帮手。

function drawDuoTone (ctx, glyph, x, y, {
    fontSize = 30,
    primaryColor = "#183153",
    secondaryColor = primaryColor,
    primaryOpacity = 1,
    secondaryOpacity = primaryOpacity
  } = {}) {
  
  ctx.font = `${fontSize}px 'Font Awesome 6 DuoTone'`;
  // ::before
  ctx.fillStyle = primaryColor;
  ctx.globalAlpha = primaryOpacity;
  ctx.fillText(glyph, x, y);
  // ::after
  ctx.fillStyle = secondaryColor;
  ctx.globalAlpha = secondaryOpacity;
  // currently ::after glyph code is just the main code repeated twice
  ctx.fillText(glyph.repeat(2), x, y);
}
// make sure the font is properly loaded and ready to use
document.fonts.load("30px 'Font Awesome 6 DuoTone'").then(() => {
  const ctx = document.querySelector("canvas").getContext("2d");
  drawDuoTone(ctx, "\uf047", 20, 50, { secondaryOpacity: 0.4 });
  drawDuoTone(ctx, "\uf240", 80, 50, {
    primaryColor: "limegreen",
    secondaryColor: "dimgray"
  });
});
@import "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css";
/*
  Not sure this is legal, please don't link to that file in your own project,
  I claim fair use here since it's only to expose how to make it work,
  but these fonts are supposed to be behind a paywall, so pay it please.
*/
@import "https://site-assets.fontawesome.com/releases/v6.2.1/css/all.css";
<canvas></canvas>

相关问题