使用节点canvas进行反应:registerFont causesTypeError:Object(..)不是函数



我正在用React制作一个文字游戏,我需要在画布元素上绘制游戏,然后将其作为图像。除了在图像中添加字体之外,它基本上是有效的。

更具体地说,我的游戏是在next.js上使用React构建的,它只需使用系统字体即可在本地工作。但我也需要它来处理服务器端渲染,而且服务器上没有安装系统字体。这意味着它在文本应该在的地方用小正方形绘制图像和文本。

我的问题是画布包中的registerFont。我的代码的相关部分是

import { registerFont, createCanvas } from 'canvas';
//import RobotoR from '../../public/Roboto/Roboto-Regular.ttf';
export const drawCanvas = ({ sentence, cards, workingCards, width, height }) => {
// default canvas size
let cw = 1200 // canvas width
let ch = 630 // canvas height; this is a minimun, it might change
~~~
registerFont('../../public/Roboto/Roboto-Regular.ttf', { family: 'Roboto' })
const canvas = createCanvas(cw, ch)
const ctx = canvas.getContext('2d')

对createCanvas的调用有效,对registerFont的调用无效。我查看了node_modules/画布,registerFont的导出略有不同,但它似乎适用于其他所有人。

node_modules/ccanvas/index.js:

function createCanvas (width, height, type) {
return new Canvas(width, height, type)
}
~

/**
* Resolve paths for registerFont. Must be called *before* creating a Canvas
* instance.
* @param src {string} Path to font file.
* @param fontFace {{family: string, weight?: string, style?: string}} Object
* specifying font information. `weight` and `style` default to `"normal"`.
*/
function registerFont (src, fontFace) {
// TODO this doesn't need to be on Canvas; it should just be a static method
// of `bindings`.
return Canvas._registerFont(fs.realpathSync(src), fontFace)
}
~
module.exports = {
Canvas,
...
registerFont,
...
createCanvas,
...

我可能犯了一些非常愚蠢的小错误,但我找不到。救命?

回答我自己,以防有人遇到同样的问题。我问了一个比我更了解的人,在一起思考了半个小时后,他意识到如果节点画布在浏览器中运行,它有一个单独的入口点。我不知道这是一件事,但事实确实如此。

在node-canvas package.json中,有一行"browser":"browser.js",它告诉它在浏览器中运行时导出一组有限的函数。

我的绘图功能用于浏览器和单独的服务器端api进程。但我不需要在浏览器中注册字体,因为已经安装了字体,所以我导入"registerFont",然后检查它是否返回未定义。如果它被定义了,我会使用它,如果没有,我必须在浏览器中,不需要它

最新更新