Skip to content

leafer-ui

Web 版  |  Worker 版  |  Node 版  |  小程序版

如果您仅需绘图功能,推荐更轻量的 leafer-draw

安装

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

sh
npm install @leafer-ui/node
sh
pnpm add @leafer-ui/node
sh
yarn add @leafer-ui/node
sh
bun add @leafer-ui/node

skia  |  napi

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

sh
npm install skia-canvas
sh
pnpm add skia-canvas
sh
yarn add skia-canvas
sh
bun add skia-canvas

体验

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

js
const { Leafer, Rect, useCanvas } = require('@leafer-ui/node')
const skia = require('skia-canvas')
const http = require('http')

useCanvas('skia', skia) // must

http.createServer(function (req, res) {

    const leafer = new Leafer({ width: 800, height: 600 })
    leafer.add(Rect.one({ fill: '#32cd79' }, 100, 100))

    leafer.export('png').then(function (result) {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.write(`<img src="${result.data}" />`)
        res.end()
    })

}).listen(3000, function () {
    console.log('\x1B[36m%s\x1B[0m', 'server is running at http://localhost:3000')
})
js
import { Leafer, Rect, useCanvas } from '@leafer-ui/node'
import skia from 'skia-canvas'
import http from 'http'

useCanvas('skia', skia) // must

http.createServer(function (req, res) {

    const leafer = new Leafer({ width: 800, height: 600 })
    leafer.add(Rect.one({ fill: '#32cd79' }, 100, 100))

    leafer.export('png').then(function (result) {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.write(`<img src="${result.data}" />`)
        res.end()
    })

}).listen(3000, function () {
    console.log('\x1B[36m%s\x1B[0m', 'server is running at http://localhost:3000')
})

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

sh
node index.js
sh
node index.mjs

使用自定义字体

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

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

Released under the MIT License.