@leafer-ui/node

在服务端 node 环境中运行,可用于后台绘图、生成图片、自动化测试,能够 模拟用户交互

安装

npm

  1. npm install @leafer-ui/node

pnpm

  1. pnpm add @leafer-ui/node

yarn

  1. yarn add @leafer-ui/node

bun

  1. bun add @leafer-ui/node

skia | napi

skia-canvas 用于在服务端环境中替代 Canvas 的功能, 底层基于 skia,需单独安装,安装编译时间会比较长,请耐心等待。

npm

  1. npm install skia-canvas

pnpm

  1. pnpm add skia-canvas

yarn

  1. yarn add skia-canvas

bun

  1. bun add skia-canvas

体验

创建入口文件,实现一个包含矩形的画布,并生成图片显示。

index.js

  1. const { Leafer, Rect, useCanvas } = require('@leafer-ui/node')
  2. const skia = require('skia-canvas')
  3. const http = require('http')
  4. useCanvas('skia', skia) // must
  5. http.createServer(function (req, res) {
  6. const leafer = new Leafer({ width: 800, height: 600 })
  7. leafer.add(Rect.one({ fill: '#32cd79' }, 100, 100))
  8. leafer.export('png').then(function (result) {
  9. res.writeHead(200, { 'Content-Type': 'text/html' })
  10. res.write(`<img src="${result.data}" />`)
  11. res.end()
  12. })
  13. }).listen(3000, function () {
  14. console.log('\x1B[36m%s\x1B[0m', 'server is running at http://localhost:3000')
  15. })

index.mjs

  1. import { Leafer, Rect, useCanvas } from '@leafer-ui/node'
  2. import skia from 'skia-canvas'
  3. import http from 'http'
  4. useCanvas('skia', skia) // must
  5. http.createServer(function (req, res) {
  6. const leafer = new Leafer({ width: 800, height: 600 })
  7. leafer.add(Rect.one({ fill: '#32cd79' }, 100, 100))
  8. leafer.export('png').then(function (result) {
  9. res.writeHead(200, { 'Content-Type': 'text/html' })
  10. res.write(`<img src="${result.data}" />`)
  11. res.end()
  12. })
  13. }).listen(3000, function () {
  14. console.log('\x1B[36m%s\x1B[0m', 'server is running at http://localhost:3000')
  15. })

运行以下命令,然后在浏览器访问 localhost:3000

js

  1. node index.js

mjs

  1. node index.mjs

使用自定义字体

通过 skia-canvas 的 FontLibrary.use() 方法加载字体后,再设置 fontFamily 即可。

https://www.npmjs.com/package/skia-canvas#FontLibrary