Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Enlightened library to convert HTML and CSS to SVG

License

NotificationsYou must be signed in to change notification settings

vercel/satori

Satori

Satori: Enlightened library to convert HTML and CSS to SVG.

Note

To use Satori in your project to generate PNG images like Open Graph images and social cards, check out ourannouncement andVercel’s Open Graph Image Generation →

To use it in Next.js, take a look at theNext.js Open Graph Image Generation template →

Overview

Satori supports the JSX syntax, which makes it very straightforward to use. Here’s an overview of the basic usage:

// api.jsximportsatorifrom'satori'constsvg=awaitsatori(<divstyle={{color:'black'}}>hello, world</div>,{width:600,height:400,fonts:[{name:'Roboto',// Use `fs` (Node.js only) or `fetch` to read the font as Buffer/ArrayBuffer and provide `data` here.data:robotoArrayBuffer,weight:400,style:'normal',},],},)

Satori will render the element into a 600×400 SVG, and return the SVG string:

'<svg ...><path d="..." fill="black"></path></svg>'

Under the hood, it handles layout calculation, font, typography and more, to generate a SVG that matches the exact same HTML and CSS in a browser.


Documentation

JSX

Satori only accepts JSX elements that are pure and stateless. You can use a subset of HTMLelements (see section below), or custom React components, but React APIs such asuseState,useEffect,dangerouslySetInnerHTML are not supported.

Use without JSX

If you don't have JSX transpiler enabled, you can simply passReact-elements-like objects that havetype,props.children andprops.style (and other properties too) directly:

awaitsatori({type:'div',props:{children:'hello, world',style:{color:'black'},},},options)

HTML Elements

Satori supports a limited subset of HTML and CSS features, due to its special use cases. In general, only these static and visible elements and properties that are implemented.

For example, the<input> HTML element, thecursor CSS property are not in consideration. And you can't use<style> tags or external resources via<link> or<script>.

Also, Satori does not guarantee that the SVG will 100% match the browser-rendered HTML output since Satori implements its own layout engine based on theSVG 1.1 spec.

You can find the list of supported HTML elements and their preset styleshere.

Images

You can use<img> to embed images. However,width, andheight attributes are recommended to set:

awaitsatori(<imgsrc="https://picsum.photos/200/300"width={200}height={300}/>,options)

When usingbackground-image, the image will be stretched to fit the element by default if you don't specify the size.

If you want to render the generated SVG to another image format such as PNG, it would be better to use base64 encoded image data (or buffer) directly asprops.src so no extra I/O is needed in Satori:

awaitsatori(<imgsrc="data:image/png;base64,..."width={200}height={300}/>,// Or src={arrayBuffer}, src={buffer}options)

CSS

Satori uses the same Flexboxlayout engine as React Native, and it’snot a complete CSS implementation. However, it supports a subset of the spec that covers most common CSS features:

PropertyProperty ExpandedSupported ValuesExample
displayflex,contents,none, default toflex
positionrelative,static andabsolute, default torelative
colorSupported
margin
marginTopSupported
marginRightSupported
marginBottomSupported
marginLeftSupported
Position
topSupported
rightSupported
bottomSupported
leftSupported
Size
widthSupported
heightSupported
Min & max size
minWidthSupported except formin-content,max-content andfit-content
minHeightSupported except formin-content,max-content andfit-content
maxWidthSupported except formin-content,max-content andfit-content
maxHeightSupported except formin-content,max-content andfit-content
border
Width (borderWidth,borderTopWidth, ...)Supported
Style (borderStyle,borderTopStyle, ...)solid anddashed, default tosolid
Color (borderColor,borderTopColor, ...)Supported
Shorthand (border,borderTop, ...)Supported, i.e.1px solid gray
borderRadius
borderTopLeftRadiusSupported
borderTopRightRadiusSupported
borderBottomLeftRadiusSupported
borderBottomRightRadiusSupported
ShorthandSupported, i.e.5px,50% / 5px
Flex
flexDirectioncolumn,row,row-reverse,column-reverse, default torow
flexWrapwrap,nowrap,wrap-reverse, default towrap
flexGrowSupported
flexShrinkSupported
flexBasisSupported except forauto
alignItemsstretch,center,flex-start,flex-end,baseline,normal, default tostretch
alignContentSupported
alignSelfSupported
justifyContentSupported
gapSupported
Font
fontFamilySupported
fontSizeSupported
fontWeightSupported
fontStyleSupported
Text
tabSizeSupported
textAlignstart,end,left,right,center,justify, default tostart
textTransformnone,lowercase,uppercase,capitalize, defaults tonone
textOverflowclip,ellipsis, defaults toclip
textDecorationSupport line typesunderline andline-through, and stylesdotted,dashed,double,solidExample
textShadowSupported
lineHeightSupported
letterSpacingSupported
whiteSpacenormal,pre,pre-wrap,pre-line,nowrap, defaults tonormal
wordBreaknormal,break-all,break-word,keep-all, defaults tonormal
textWrapwrap,balance, defaults towrap
Background
backgroundColorSupported, single value
backgroundImagelinear-gradient,repeating-linear-gradient,radial-gradient,repeating-radial-gradient,url, single value
backgroundPositionSupport single value
backgroundSizeSupport two-value size i.e.10px 20%
backgroundClipborder-box,text
backgroundRepeatrepeat,repeat-x,repeat-y,no-repeat, defaults torepeat
transform
Translate (translate,translateX,translateY)Supported
RotateSupported
Scale (scale,scaleX,scaleY)Supported
Skew (skew,skewX,skewY)Supported
transformOriginSupport one-value and two-value syntax (both relative and absolute values)
objectFitcontain,cover,none, default tonone
objectPositionSupport keywords:top,bottom,left,right,center, and combinations liketop left. Defaults tocenter.
opacitySupported
boxSizingSupported
boxShadowSupported
overflowvisible andhidden, default tovisible
filterSupported
clipPathSupportedExample
lineClampSupportedExample
Mask
maskImagelinear-gradient(...),radial-gradient(...),url(...)Example
maskPositionSupportedExample
maskSizeSupport two-value size i.e.10px 20%Example
maskRepeatrepeat,repeat-x,repeat-y,no-repeat, defaults torepeatExample
WebkitTextStrokeWebkitTextStrokeWidthSupported
WebkitTextStrokeColorSupported

Note:

  1. Three-dimensional transforms are not supported.
  2. There is noz-index support in SVG. Elements that come later in the document will be painted on top.
  3. calc isn't supported.
  4. currentColor support is only available for thecolor property.

Language and Typography

Advanced typography features such as kerning, ligatures and other OpenType features are not currently supported.

RTL languages are not supported either.

Fonts

Satori currently supports three font formats: TTF, OTF and WOFF. Note that WOFF2 is not supported at the moment. You must specify the font if any text is rendered with Satori, and pass the font data as ArrayBuffer (web) or Buffer (Node.js):

awaitsatori(<divstyle={{fontFamily:'Inter'}}>Hello</div>,{width:600,height:400,fonts:[{name:'Inter',data:inter,weight:400,style:'normal',},{name:'Inter',data:interBold,weight:700,style:'normal',},],})

Multiple fonts can be passed to Satori and used infontFamily.

Tip

We recommend you define global fonts instead of creating a new object and pass it to satori for better performance, if your fonts do not change.Read it for more detail

Emojis

To render custom images for specific graphemes, you can usegraphemeImages option to map the grapheme to an image source:

awaitsatori(<div>Next.js is 🤯!</div>,{    ...,graphemeImages:{'🤯':'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/svg/1f92f.svg',},})

The image will be resized to the current font-size (both width and height) as a square.

Locales

Satori supports rendering text in different locales. You can specify the supported locales via thelang attribute:

awaitsatori(<divlang="ja-JP"></div>)

Same characters can be rendered differently in different locales, you can specify the locale when necessary to force it to render with a specific font and locale. Check outthis example to learn more.

Supported locales are exported as theLocale enum type.

Dynamically Load Emojis and Fonts

Satori supports dynamically loading emoji images (grapheme pictures) and fonts. TheloadAdditionalAsset function will be called when a text segment is rendered but missing the image or font:

awaitsatori(<div>👋 你好</div>,{// `code` will be the detected language code, `emoji` if it's an Emoji, or `unknown` if not able to tell.// `segment` will be the content to render.loadAdditionalAsset:async(code:string,segment:string)=>{if(code==='emoji'){// if segment is an emojireturn`data:image/svg+xml;base64,...`}// if segment is normal textreturnloadFontFromSystem(code)}})

Runtime Support

Satori can be directly used in browser, Node.js (>= 16), and Web Workers. It bundles its underlying WASM dependencies as base64-encoded strings and loads them at runtime.

If there is a limitation on dynamically loading WASM (e.g. Cloudflare Workers), you can use the Standalone Build which is mentioned below.

Standalone Build of Satori

Satori's standalone build doesn't include Yoga's WASM binary by default, and you need to load it manually before using Satori.

First, you need to download theyoga.wasm binary fromSatori build and provide it yourself. Let's usefetch to load it directly from the CDN as an example:

importsatori,{init}from'satori/standalone'constres=awaitfetch('https://unpkg.com/satori/yoga.wasm')constyogaWasm=awaitres.arrayBuffer()awaitinit(yogaWasm)// Now you can use satori as usualconstsvg=awaitsatori(...)

Of course, you can also load theyoga.wasm file from your local disk viafs.readFile in Node.js or other methods.

Font Embedding

By default, Satori renders the text as<path> in SVG, instead of<text>. That means it embeds the font path data as inlined information, so succeeding processes (e.g. render the SVG on another platform) don’t need to deal with font files anymore.

You can turn off this behavior by settingembedFont tofalse, and Satori will use<text> instead:

constsvg=awaitsatori(<divstyle={{color:'black'}}>hello, world</div>,{    ...,embedFont:false,},)

Pixel Grid Rounding

SetpointScaleFactor to control how layout values are rounded to the pixel grid. This parameter is passed directly toYoga’spointScaleFactor and improves rendering precision on high-DPI displays.

constsvg=awaitsatori(<divstyle={{color:'black'}}>hello, world</div>,{    ...,pointScaleFactor:2,},)

Debug

To draw the bounding box for debugging, you can passdebug: true as an option:

constsvg=awaitsatori(<divstyle={{color:'black'}}>hello, world</div>,{    ...,debug:true,},)

Contribute

You can use theVercel OG Image Playground to test and report bugs of Satori. Please follow ourcontribution guidelines before opening a Pull Request.


Author



[8]ページ先頭

©2009-2025 Movatter.jp