jquery - 如何在 Canvas 中使用具有 CSS 中描述的字体的文本元素

标签 jquery html css linux html5-canvas

这是在 Bismon 内元素(由 H2020 欧洲元素资助的 GPLv3+ 软件),git commit 0e9a8eccc2976f .这个draft report描述软件。 This question提供更多的背景和动机。
这是关于(手写)webroot/jscript/bismon-hwroot.js文件,用于一些 HTML 页面,其代码由 Bismon(libonion 之上的一个专门的 Web 服务器)生成。

我为 span 添加了一些 CSS 类,例如span.bmcl_evalprompt (例如在我的文件中 first-theme.css )。

如何编写 JavaScript 代码以在 Canvas 中添加与 span.bmcl_evalprompt 具有相同样式(相同字体、颜色等)的文本片段(最好使用带有 jquery 的 jcanvas) ?我需要在我的 DOM 中创建这样的 span 元素吗?这甚至可能吗?

我只关心 Linux 上最近的 Firefox(至少 68 个)。 JQuery是 3.4。我也在使用Jquery UI 1.12.1

我的想法是创建一个单曲<span class='bmcl_evalprompt'>坐标远离浏览器视口(viewport)(或 X11 窗口)的元素,例如在 x= -10000y= -10000 (以像素为单位),然后将单个定位错误的元素添加到文档 DOM 中,然后使用传统的 Jquery 技术来获取字体系列、字体大小和元素大小。但是有没有更好的方法?或者一些 Jquery 兼容库这样做?

最佳答案

如果您只是想在 Canvas 中渲染跨度中的文本,您可以使用函数 window.getComputedStyle 访问样式属性。 .要使原始跨度不可见,请将其样式设置为 display: none .

// get the span element
const span = document.getElementsByClassName('bmcl_evalprompt')[0];

// get the relevant style properties
const font = window.getComputedStyle(span).font;
const color = window.getComputedStyle(span).color;

// get the element's text (if necessary)
const text = span.innerHTML;

// get the canvas element
const canvas = document.getElementById('canvas');

// set the canvas styling
const ctx = canvas.getContext('2d');
ctx.font = font;
ctx.fillStyle = color;

// print the span's content with correct styling
ctx.fillText(text, 35, 110);
#canvas {
  width: 300px;
  height: 200px;
  background: lightgrey;
}

span.bmcl_evalprompt {
  display: none;           // makes the span invisible
  font-family: monospace;  // change this value to see the difference
  font-size: 32px;         // change this value to see the difference
  color: rebeccapurple;    // change this value to see the difference
}
<span class="bmcl_evalprompt">Hello World!</span>
<canvas id="canvas" width="300" height="200"></canvas>

关于jquery - 如何在 Canvas 中使用具有 CSS 中描述的字体的文本元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59666877/

相关文章:

javascript - 有没有更快的方法来显示数组的每个索引

html - 溢出 :scroll not showing a disabled scroll on Chrome Mobile

javascript - 一段时间后如何更改图像背景?

php - PHP json_encode 输出错误

javascript - 使用 JQuery 通过 AJAX 获取文件

html - 为什么表格会在左右两侧添加额外的空间?

html - 在 Cloudfront 的页面上托管 Facebook iframe

javascript - 如何仅使 li 值可点击并生成 anchor ?

堆叠列表中的 CSS 选择器

html - 带有可扩展列表和带有描述的图标的温泉 UI