@halfmatthalfcat/svg-cf
v0.1.3
Published
SVG.js + svgdom + AsyncLocalStorage for Cloudflare Workers
Downloads
5
Maintainers
Readme
svg-cf
SVG.js + svgdom + AsyncLocalStorage for usage in Cloudflare Workers
svg-cf
is a combination of libraries and Node APIs to enable isolated SVG creation in Cloudflare Workers.
Originally in SVG.js + svgdom, you needed to create a new svgdom window/document instance via createSVGWindow
and then attach that window to a global, singleton instance (registerWindow
),
which doesn't necessarily work in async contexts as you may have concurrent requests operating on the same document.
svg-cf
leverages Node's AsyncLocalStorage
construct to persist a window
in any given async context so that each async context can operate on windows independently of each other.
svg-cf
also utilizes svgdom-cf
, a fork of svgdom that is compatible
for running in Cloudflare Workers. Check out the @halfmatthalfcat/svgdom-cf repo for more info.
Usage
import { SVG, withWindow } from '@halfmatthalfcat/svg-cf'
export default {
async fetch(req) {
return withWindow(() => {
const svg = SVG().size(100, 100)
svg.rect(100, 100).fill('green')
return Response(svg.svg(), {
headers: {
'Content-Type': 'image/svg+xml'
}
})
})
}
}
Fonts
Via Node
Refer to the documentation in svgdom-cf regarding fonts.
import { svgdom } from '@halfmatthalfcat/svg-cf'
import fs from 'node:fs'
svgdom.config.setFonts(fs.readFileSync('path/to/font.ttf'))
Via Wrangler/CF
Refer to the documentation in svgdom-cf regarding fonts.
Wrangler Config
rules = [
{ type = "Data", globs = ["**/*.ttf"], fallthrough = true }
]
Worker Script
import { svgdom } from '@halfmatthalfcat/svg-cf'
import Ariel from './Ariel.ttf'
svgdom.config.setFonts(Ariel)
Installation
Npm:
npm install @halfmatthalfcat/svg-cf
Yarn:
yarn add @halfmatthalfcat/svg-cf