the editable site (validation-lab)
This commit is contained in:
commit
3ac81d5a52
13454 files changed
+2227005
No files matched your search
+55
@@ -0,0 +1,55 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 lynweklm@gmail.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
src/svg_doc/broken_image.png is Chromium's broken-image icon
|
||||
(third_party/blink/public/default_100_percent/blink/broken_image.png),
|
||||
used under the Chromium license:
|
||||
|
||||
Copyright 2015 The Chromium Authors
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google LLC nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+528
@@ -0,0 +1,528 @@
|
||||
# `skr canvas`
|
||||
|
||||
[](https://github.com/Brooooooklyn/canvas/actions/workflows/CI.yaml)
|
||||

|
||||
[](https://npmcharts.com/compare/@napi-rs/canvas?minimal=true)
|
||||
|
||||
> 🚀 Help me to become a full-time open-source developer by [sponsoring me on Github](https://github.com/sponsors/Brooooooklyn)
|
||||
|
||||
Google Skia binding to Node.js via [Node-API](https://napi.rs), **0 System dependencies!**
|
||||
|
||||
[中文文档](./README-zh.md)
|
||||
|
||||
# Install
|
||||
|
||||
```bash
|
||||
yarn add @napi-rs/canvas
|
||||
npm install @napi-rs/canvas
|
||||
```
|
||||
|
||||
# Support matrix
|
||||
|
||||
## System requirement
|
||||
|
||||
### `arm64`
|
||||
|
||||
[**_cortex-a57_**](https://en.wikipedia.org/wiki/ARM_Cortex-A57) or newer CPU architecture on **Linux**.
|
||||
|
||||
All Apple M chips on **macOS**.
|
||||
|
||||
### `armv7`
|
||||
|
||||
[**_cortex-a7_**](https://en.wikipedia.org/wiki/ARM_Cortex-A7) or newer CPU architecture.
|
||||
|
||||
### glibc
|
||||
|
||||
Since Skia relies on the [glibc](https://www.gnu.org/software/libc/) 2.18 API, you need to have at least glibc version >= 2.18 on your system.
|
||||
|
||||
Note: the armv7 (`linux-arm-gnueabihf`) packages from 0.1.66 to 1.1.0 need
|
||||
a newer glibc (0.1.66 needs 2.28, 1.1.0 needs 2.30). Later versions need
|
||||
glibc 2.18, like the other targets.
|
||||
|
||||
## AWS Lambda usage
|
||||
|
||||
To use this library on Lambda you will need to use a Lambda layer.
|
||||
|
||||
You can simply attach a lambda layer by getting an ARN from [Canvas-Lambda-Layer](https://github.com/ShivamJoker/Canvas-Lambda-Layer)
|
||||
|
||||
> Make sure to exclude `@napi-rs/canvas` while bundling your Lambda.
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
const { promises } = require('node:fs')
|
||||
const { join } = require('node:path')
|
||||
const { createCanvas, loadImage } = require('@napi-rs/canvas')
|
||||
|
||||
const canvas = createCanvas(300, 320)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
ctx.lineWidth = 10
|
||||
ctx.strokeStyle = '#03a9f4'
|
||||
ctx.fillStyle = '#03a9f4'
|
||||
|
||||
// Wall
|
||||
ctx.strokeRect(75, 140, 150, 110)
|
||||
|
||||
// Door
|
||||
ctx.fillRect(130, 190, 40, 60)
|
||||
|
||||
// Roof
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(50, 140)
|
||||
ctx.lineTo(150, 60)
|
||||
ctx.lineTo(250, 140)
|
||||
ctx.closePath()
|
||||
ctx.stroke()
|
||||
|
||||
async function main() {
|
||||
// load images from disk or from a URL
|
||||
const catImage = await loadImage('path/to/cat.png')
|
||||
const dogImage = await loadImage('https://example.com/path/to/dog.jpg')
|
||||
|
||||
ctx.drawImage(catImage, 0, 0, catImage.width, catImage.height)
|
||||
|
||||
ctx.drawImage(dogImage, canvas.width / 2, canvas.height / 2, dogImage.width, dogImage.height)
|
||||
|
||||
// export canvas as image
|
||||
const pngData = await canvas.encode('png') // JPEG, AVIF and WebP are also supported
|
||||
// encoding in libuv thread pool, non-blocking
|
||||
await promises.writeFile(join(__dirname, 'simple.png'), pngData)
|
||||
}
|
||||
|
||||
main()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Image metadata
|
||||
|
||||
`toBuffer`, `encode` and `encodeSync` can write the resolution (DPI) and a few text fields into PNG and JPEG output. Put them in the options object:
|
||||
|
||||
```js
|
||||
const png = canvas.toBuffer('image/png', {
|
||||
resolution: 300, // pixels per inch, the same option as node-canvas
|
||||
title: 'Floor plan',
|
||||
author: 'Jane Doe',
|
||||
description: 'Ground floor, 1:100',
|
||||
})
|
||||
|
||||
// JPEG: use encode / encodeSync to set the quality as well
|
||||
const jpeg = await canvas.encode('jpeg', { quality: 90, resolution: 300, copyright: '© 2026 Jane Doe' })
|
||||
```
|
||||
|
||||
| Option | PNG | JPEG |
|
||||
| ------------- | ------------------ | ---------------------------- |
|
||||
| `resolution` | `pHYs` chunk | JFIF density (dots per inch) |
|
||||
| `title` | `Title` text chunk | XMP `dc:title` |
|
||||
| `author` | `Author` | XMP `dc:creator` |
|
||||
| `description` | `Description` | XMP `dc:description` |
|
||||
| `copyright` | `Copyright` | XMP `dc:rights` |
|
||||
| `software` | `Software` | XMP `xmp:CreatorTool` |
|
||||
| `comment` | `Comment` | `COM` segment |
|
||||
|
||||
WebP, AVIF and GIF output ignore these options. `toDataURL`, `toDataURLAsync`, `toBlob`, `convertToBlob`, `encodeStream` and `savePng` never write metadata. To save a file with metadata, write the Buffer from `toBuffer` or `encode`. With an options object, `toBuffer('image/jpeg', ...)` encodes at quality 92; use `encode` or `encodeSync` for another quality.
|
||||
|
||||
### PNG encoding options
|
||||
|
||||
For PNG output, `toBuffer('image/png', options)`, `encode('png', options)` and `encodeSync('png', options)` also accept `compressionLevel` (zlib level `0–9`, default `6`) and `filters` (libpng row filter bitmask from `PngFilter`, default `PngFilter.All` / `0xF8`) in the same options object:
|
||||
|
||||
```js
|
||||
const { createCanvas, PngFilter } = require('@napi-rs/canvas')
|
||||
|
||||
// Fast PNG encoding (Chromium's canvas preset: zlib level 1, Up filter only)
|
||||
const png = await canvas.encode('png', {
|
||||
compressionLevel: 1,
|
||||
filters: PngFilter.Up, // 0x20
|
||||
})
|
||||
```
|
||||
|
||||
| `PngFilter` constant | Value | Description |
|
||||
| -------------------- | ------ | --------------------- |
|
||||
| `PngFilter.None` | `0x08` | None filter |
|
||||
| `PngFilter.Sub` | `0x10` | Sub filter |
|
||||
| `PngFilter.Up` | `0x20` | Up filter |
|
||||
| `PngFilter.Avg` | `0x40` | Average filter |
|
||||
| `PngFilter.Paeth` | `0x80` | Paeth filter |
|
||||
| `PngFilter.All` | `0xF8` | All filters (default) |
|
||||
|
||||
## Text rendering
|
||||
|
||||
By default text is drawn the same way on every OS. Every font is drawn with FreeType, with Skia's default text gamma, no LCD (subpixel) text and one font family table (the one Linux uses).
|
||||
|
||||
Text gives the same pixels and the same `measureText` results on macOS, Linux and Windows when all of these are true:
|
||||
|
||||
1. `ctx.font` names only fonts you registered. The canvas default `10px sans-serif`, the other generic families and names like `Arial` use installed fonts, unless you registered a font under that name.
|
||||
2. Your registered fonts have every character you draw. A character they lack is taken from an installed font.
|
||||
3. You set `ctx.lang`, for example to `'en'`. The default `'inherit'` follows the host language.
|
||||
4. You use the default `'portable'` renderer, not `setTextRenderer('system')`.
|
||||
5. The `FREETYPE_PROPERTIES` env var is not set.
|
||||
|
||||
x64 and arm64 builds can still differ by 1 color level on some edge pixels.
|
||||
|
||||
```js
|
||||
const { GlobalFonts } = require('@napi-rs/canvas')
|
||||
|
||||
// A name no OS installs
|
||||
GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'MyLato')
|
||||
ctx.font = '20px MyLato'
|
||||
ctx.lang = 'en'
|
||||
```
|
||||
|
||||
A name registered over an installed family (for example `Helvetica`) works like a CSS `@font-face` in Chrome: only font lists that name it use it, for every style (the faces are chosen as described below; bold or italic is made from the chosen face when that file is not bold or italic). The generic families, such as `sans-serif`, keep the installed family. To change a generic family, register the font under the keyword itself:
|
||||
|
||||
```js
|
||||
GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'sans-serif')
|
||||
```
|
||||
|
||||
For the unquoted keyword (`sans-serif`), each face of that font is matched by the file's own style and descriptors are ignored; bold is made from weight 600, as for other registered fonts. Only the quoted name (`"sans-serif"`) follows the descriptor and newest-face rule below.
|
||||
|
||||
Faces of one family are chosen by their descriptors, as with `@font-face`. Without descriptors every face is `auto` and the newest face wins; give `{ weight, style, stretch }` for each file of a family, or use `loadFontsFromDir` (installed fonts match by the file's own style):
|
||||
|
||||
```js
|
||||
GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'MyLato', { weight: 400 })
|
||||
GlobalFonts.registerFromPath('./fonts/Lato-Bold.ttf', 'MyLato', { weight: 700 })
|
||||
```
|
||||
|
||||
> **Behavior change**: registered faces with no descriptors are all `auto`, so in such a family the face registered last draws every style (made bold or italic when that file is not), as Chrome draws `@font-face` rules with no descriptors. Before, each face was picked by the file's own style.
|
||||
|
||||
These still depend on the OS and the machine:
|
||||
|
||||
- Installed fonts. Names like `Arial` or `Helvetica`, and the generic families (`sans-serif`, `serif`, `monospace`, `system-ui`, the canvas default `10px sans-serif`) resolve to whatever is installed.
|
||||
- Characters your registered fonts lack. They are taken from an installed font (the ones `loadSystemFonts` and `loadFontsFromDir` load, or the OS font folder) that has them, else they draw as boxes. A font you `register` or `registerFromPath` is never used for a character another font lacks, as in Chrome: to give a host without fonts a fallback font, load it with `loadFontsFromDir`.
|
||||
- The `ex`, `ch`, `cap` and line-height units inside SVG images use an installed default font.
|
||||
- Lottie (Skottie) text uses installed fonts.
|
||||
- PDF font embedding depends on the build target.
|
||||
- x64 and arm64 builds can differ by 1 color level on some edge pixels.
|
||||
- A `FREETYPE_PROPERTIES` env var changes FreeType's hinting.
|
||||
- The host language. The default `ctx.lang` (`'inherit'`) follows the OS UI language (the macOS language list, the Windows user locale, or `LANGUAGE` / `LC_ALL` / `LC_MESSAGES` / `LANG` elsewhere), as Chrome does. It changes `locl` glyphs, case mapping (`small-caps` under `tr`) and CJK punctuation spacing. Set `ctx.lang` (for example `'en'`) to pin it. The installed font picked for a Han character still follows the host language unless `ctx.lang` names a CJK language (for example `'ja'` or `'zh-Hans'`). On macOS with `setTextRenderer('system')`, the generic families also follow a `ja`, `ko`, `zh-CN`, `zh-TW`, `ar`, `he` or `fa` UI language whatever `ctx.lang` is, as in Chrome (`serif` is Hiragino Mincho ProN under a Japanese UI).
|
||||
|
||||
Set `DISABLE_SYSTEM_FONTS_LOAD=1` to keep installed fonts out of `GlobalFonts.families`. By default they can still be found by name, on every OS.
|
||||
|
||||
### `setTextRenderer()`
|
||||
|
||||
`setTextRenderer('system')` draws text the way Chrome does on each OS: CoreText on macOS (with CoreText's installed fonts and fallback), Fontations on Linux and DirectWrite on Windows (with Fontations for color/CFF2/avar2 web fonts), plus each OS's text gamma, LCD text on opaque macOS canvases, Chrome's per-OS font families and the macOS metric rules. This was the default on macOS and Linux in 1.0.12 and 1.0.13. `'portable'` is the default.
|
||||
|
||||
```js
|
||||
const { setTextRenderer, getTextRenderer } = require('@napi-rs/canvas')
|
||||
|
||||
setTextRenderer('system')
|
||||
getTextRenderer() // 'system'
|
||||
```
|
||||
|
||||
It applies to the whole process. Call it once at startup, before you create canvases. `setTextRenderer('portable')` switches back. Any other value throws a `TypeError`. A canvas created before the switch keeps its old text gamma until you set its width or height. A `ctx.font` value set before the switch keeps its parsed form (sizes in `ex`, `ch` and other font-relative units, and on macOS the `BlinkMacSystemFont` to `system-ui` rewrite), so set `ctx.font` again after the switch.
|
||||
|
||||
> **Behavior change** ([#1402](https://github.com/Brooooooklyn/canvas/issues/1402)): text on macOS and Linux is drawn the way Windows draws it, so pixels and `measureText` results differ from 1.0.12 and 1.0.13. On macOS, the installed fonts are FreeType faces again (as in 1.0.11), read from `/System/Library/Fonts`, `/Library/Fonts` and `~/Library/Fonts`; CoreText's per-character fallback is off, and `sans-serif`, `serif` and `monospace` map to Arial, Times New Roman and the Linux monospace list. On macOS, `DISABLE_SYSTEM_FONTS_LOAD` no longer hides installed fonts from name lookup, as on Linux and Windows and before 1.0.12; it only keeps them out of `GlobalFonts.families`. Call `setTextRenderer('system')` to draw with each OS's own font renderer and installed fonts again, as 1.0.12 and 1.0.13 did. Both renderers now shape text the way Chrome does, so the output is not the same as in 1.0.12 and 1.0.13.
|
||||
|
||||
> **Behavior change**: a character no font of the font list has is taken from an installed font, as Chrome's font cache takes it from the platform's fonts. This applies to the portable renderer on every OS and to the system renderer off macOS (on macOS, CoreText still picks first). The font is chosen the way Chrome on Windows chooses it: a bold or italic list first tries its first family at the normal style, then the font Windows names for the character's script (on macOS, the font Chrome's CoreText fallback names for it), then the first installed family, by name, that has the character. Before, such a character drew as a box (the first font's `.notdef`). Private use characters still draw as boxes.
|
||||
|
||||
> **Behavior change**: SVG text (SVG images, the SVG images nested in them, and `convertSVGTextToPath`) takes a character its first font lacks from the next family of its `font-family` list, then from the system's fonts, as canvas text does. Chrome does the same. Before, the whole text used the first font, and a character it lacks drew as a box. Text with no such character draws the same as before. `convertSVGTextToPath` now reads the document the way an SVG image does (`<style>` sheets, `var()`, `<use>` and the other CSS rules), so its output matches what the SVG image draws. A document that is not well-formed UTF-8 XML is read as before, with only the first family of each `font-family` list.
|
||||
|
||||
> **Behavior change**: the default `ctx.lang`, `'inherit'`, follows the host language, as Chrome does. Before, it meant no language. Text whose font has language-specific glyphs or spacing can draw and measure differently on hosts with different UI languages; set `ctx.lang` to pin it.
|
||||
|
||||
> **Behavior change**: SVG text whose family lacks the bold or italic face it asks for draws a synthetic bold or italic, with the rules canvas text uses: a registered font is bolded at `font-weight` 600 and up and slanted for `italic` and `oblique` unless it has that face (or a `wght` axis above 400, or a `slnt` axis); an installed font follows its own faces. Chrome does the same. The advances do not change, so the text does not move; the glyphs are heavier or slanted, and `convertSVGTextToPath` outlines grow to match. Before, SVG text drew the regular face for every style.
|
||||
|
||||
## Emoji text
|
||||
|
||||
```js
|
||||
const { writeFileSync } = require('fs')
|
||||
const { join } = require('path')
|
||||
|
||||
const { createCanvas, GlobalFonts } = require('@napi-rs/canvas')
|
||||
|
||||
GlobalFonts.registerFromPath(join(__dirname, '..', 'fonts', 'AppleColorEmoji@2x.ttf'), 'Apple Emoji')
|
||||
GlobalFonts.registerFromPath(join(__dirname, '..', '__test__', 'fonts', 'COLRv1.ttf'), 'COLRv1')
|
||||
|
||||
console.info(GlobalFonts.families)
|
||||
|
||||
const canvas = createCanvas(760, 360)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
ctx.font = '50px Apple Emoji'
|
||||
ctx.strokeText('😀😃😄😁😆😅😂🤣☺️😊😊😇', 50, 150)
|
||||
|
||||
ctx.font = '100px COLRv1'
|
||||
ctx.fillText('abc', 50, 300)
|
||||
|
||||
const b = canvas.toBuffer('image/png')
|
||||
|
||||
writeFileSync(join(__dirname, 'draw-emoji.png'), b)
|
||||
```
|
||||
|
||||

|
||||
|
||||
# Features
|
||||
|
||||
## Path2D
|
||||
|
||||
```typescript
|
||||
new Path2D()
|
||||
new Path2D(path: Path2D)
|
||||
// new Path2D('M108.956,403.826c0,0,0.178,3.344-1.276,3.311 c-1.455-0.033-30.507-84.917-66.752-80.957C40.928,326.18,72.326,313.197,108.956,403.826z')
|
||||
new Path2D(path: string)
|
||||
```
|
||||
|
||||
```typescript
|
||||
export interface DOMMatrix2DInit {
|
||||
a: number
|
||||
b: number
|
||||
c: number
|
||||
d: number
|
||||
e: number
|
||||
f: number
|
||||
}
|
||||
|
||||
export class Path2D {
|
||||
constructor(path?: Path2D | string)
|
||||
|
||||
addPath(path: Path2D, transform?: DOMMatrix2DInit): void
|
||||
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void
|
||||
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
|
||||
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
|
||||
closePath(): void
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
rotation: number,
|
||||
startAngle: number,
|
||||
endAngle: number,
|
||||
anticlockwise?: boolean,
|
||||
): void
|
||||
lineTo(x: number, y: number): void
|
||||
moveTo(x: number, y: number): void
|
||||
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
|
||||
rect(x: number, y: number, w: number, h: number): void
|
||||
|
||||
// PathKit methods
|
||||
op(path: Path2D, operation: PathOp): Path2D
|
||||
toSVGString(): string
|
||||
getFillType(): FillType
|
||||
getFillTypeString(): string
|
||||
setFillType(type: FillType): void
|
||||
simplify(): Path2D
|
||||
asWinding(): Path2D
|
||||
stroke(stroke?: StrokeOptions): Path2D
|
||||
transform(transform: DOMMatrix2DInit): Path2D
|
||||
getBounds(): [left: number, top: number, right: number, bottom: number]
|
||||
computeTightBounds(): [left: number, top: number, right: number, bottom: number]
|
||||
trim(start: number, end: number, isComplement?: boolean): Path2D
|
||||
round(radius: number): Path2D
|
||||
equals(path: Path2D): boolean
|
||||
}
|
||||
```
|
||||
|
||||
## PathKit
|
||||
|
||||
`PathKit` is a toolset for manipulating Path in `Skia`, supporting **_quadratic beziers_**, **_cubic beziers_** and **_conics_**.
|
||||
The main features are.
|
||||
|
||||
### Path Operation
|
||||
|
||||
`.op(path, PathOp)`
|
||||
|
||||
```js
|
||||
const pathOne = new Path2D(
|
||||
'M8 50H92C96.4183 50 100 53.5817 100 58V142C100 146.418 96.4183 150 92 150H8C3.58172 150 0 146.418 0 142V58C0 53.5817 3.58172 50 8 50Z',
|
||||
)
|
||||
const pathTwo = new Path2D(
|
||||
'"M58 0H142C146.418 0 150 3.58172 150 8V92C150 96.4183 146.418 100 142 100H58C53.5817 100 50 96.4183 50 92V8C50 3.58172 53.5817 0 58 0Z',
|
||||
)
|
||||
|
||||
pathOne.op(pathTwo, PathOp.Intersect).toSVGString()
|
||||
// => "M100 100L58 100C53.5817 100 50 96.4183 50 92L50 50L92 50C96.4183 50 100 53.5817 100 58L100 100Z"
|
||||
```
|
||||
|
||||
- **Union**, subtract the op path from the first path
|
||||
- **Difference**, intersect the two paths
|
||||
- **ReverseDifference**, union (inclusive-or) the two paths
|
||||
- **Intersect**, exclusive-or the two paths
|
||||
- **XOR**, subtract the first path from the op path
|
||||
|
||||

|
||||
|
||||
### Covert `FillType` in **_Path_**
|
||||
|
||||
`.asWinding()`
|
||||
|
||||
You can convert `fill-rule="evenodd"` to `fill-rule="nonzero"` in SVG.
|
||||
This is useful for **OpenType** font-related tools, as `fill-rule="nonzero"` is only supported in **OpenType** fonts.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
const pathCircle = new Path2D(
|
||||
'M24.2979 13.6364H129.394V40.9091H24.2979L14.6278 27.2727L24.2979 13.6364ZM21.9592 0C19.0246 0 16.2716 1.42436 14.571 3.82251L1.67756 22.0043C-0.559186 25.1585 -0.559186 29.387 1.67756 32.5411L14.571 50.7227C16.2716 53.1209 19.0246 54.5455 21.9592 54.5455H70.4673V68.1818H16.073C11.0661 68.1818 7.00728 72.2518 7.00728 77.2727V113.636C7.00728 118.657 11.0661 122.727 16.073 122.727H70.4673V150H84.0658V122.727H128.041C130.975 122.727 133.729 121.303 135.429 118.905L148.323 100.723C150.559 97.5686 150.559 93.3405 148.323 90.1864L135.429 72.0045C133.729 69.6064 130.975 68.1818 128.041 68.1818H84.0658V54.5455H133.927C138.934 54.5455 142.993 50.4755 142.993 45.4545V9.09091C142.993 4.07014 138.934 0 133.927 0H21.9592ZM125.702 109.091H20.6058V81.8182H125.702L135.372 95.4545L125.702 109.091Z',
|
||||
)
|
||||
pathCircle.setFillType(FillType.EvenOdd)
|
||||
pathCircle.asWinding().toSVGString()
|
||||
// => "M24.2979 13.6364L129.394 13.6364L129.394 40.9091L24.2979 40.9091L14.6278 27.2727L24.2979 13.6364ZM21.9592 0C19.0246 0 16.2716 1.42436 14.571 3.82251L1.67756 22.0043C-0.559186 25.1585 -0.559186 29.387 1.67756 32.5411L14.571 50.7227C16.2716 53.1209 19.0246 54.5455 21.9592 54.5455L70.4673 54.5455L70.4673 68.1818L16.073 68.1818C11.0661 68.1818 7.00728 72.2518 7.00728 77.2727L7.00728 113.636C7.00728 118.657 11.0661 122.727 16.073 122.727L70.4673 122.727L70.4673 150L84.0658 150L84.0658 122.727L128.041 122.727C130.975 122.727 133.729 121.303 135.429 118.905L148.323 100.723C150.559 97.5686 150.559 93.3405 148.323 90.1864L135.429 72.0045C133.729 69.6064 130.975 68.1818 128.041 68.1818L84.0658 68.1818L84.0658 54.5455L133.927 54.5455C138.934 54.5455 142.993 50.4755 142.993 45.4545L142.993 9.09091C142.993 4.07014 138.934 0 133.927 0L21.9592 0ZM125.702 109.091L20.6058 109.091L20.6058 81.8182L125.702 81.8182L135.372 95.4545L125.702 109.091Z"
|
||||
```
|
||||
|
||||
### Simplify **_Path_**
|
||||
|
||||
`.simplify()`
|
||||
|
||||
Set the path to the same non-overlapping contour as the original path area, which means that it can also remove overlapping paths.
|
||||
|
||||
<img width="800" src="./docs/imgs/simplify.png" >
|
||||
|
||||
[SVG with overlapping paths](./docs/imgs/overlapping-path.svg) (Left)
|
||||
|
||||
```js
|
||||
const path =
|
||||
'M2.933,89.89 L89.005,3.818 Q90.412,2.411 92.249,1.65 Q94.087,0.889 96.076,0.889 Q98.065,0.889 99.903,1.65 Q101.741,2.411 103.147,3.818 L189.22,89.89 Q190.626,91.296 191.387,93.134 Q192.148,94.972 192.148,96.961 Q192.148,98.95 191.387,100.788 Q190.626,102.625 189.219,104.032 Q187.813,105.439 185.975,106.2 Q184.138,106.961 182.148,106.961 Q180.159,106.961 178.322,106.2 Q176.484,105.439 175.077,104.032 L89.005,17.96 L96.076,10.889 L103.147,17.96 L17.075,104.032 Q15.668,105.439 13.831,106.2 Q11.993,106.961 10.004,106.961 Q8.015,106.961 6.177,106.2 Q4.339,105.439 2.933,104.032 Q1.526,102.625 0.765,100.788 Q0.004,98.95 0.004,96.961 Q0.004,94.972 0.765,93.134 Q1.526,91.296 2.933,89.89 Z'
|
||||
|
||||
path.simplify().toSVGString()
|
||||
// => "M89.005 3.818L2.933 89.89Q1.526 91.296 0.765 93.134Q0.004 94.972 0.004 96.961Q0.004 98.95 0.765 100.788Q1.526 102.625 2.933 104.032Q4.339 105.439 6.177 106.2Q8.015 106.961 10.004 106.961Q11.993 106.961 13.831 106.2Q15.668 105.439 17.075 104.032L96.076 25.031L175.077 104.032Q176.484 105.439 178.322 106.2Q180.159 106.961 182.148 106.961Q184.138 106.961 185.975 106.2Q187.813 105.439 189.219 104.032Q190.626 102.625 191.387 100.788Q192.148 98.95 192.148 96.961Q192.148 94.972 191.387 93.134Q190.626 91.296 189.22 89.89L103.147 3.818Q101.741 2.411 99.903 1.65Q98.065 0.889 96.076 0.889Q94.087 0.889 92.249 1.65Q90.412 2.411 89.005 3.818Z"
|
||||
```
|
||||
|
||||
## Lottie Animation
|
||||
|
||||
Render [Lottie](https://airbnb.io/lottie/) animations using Skia's [Skottie](https://skia.org/docs/user/modules/skottie/) module.
|
||||
|
||||
### Load Animation
|
||||
|
||||
```js
|
||||
const { LottieAnimation } = require('@napi-rs/canvas')
|
||||
|
||||
// Load from file
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
|
||||
// Load from JSON string with resource path for external assets
|
||||
const animation = LottieAnimation.loadFromData(jsonString, {
|
||||
resourcePath: '/path/to/assets',
|
||||
})
|
||||
```
|
||||
|
||||
### Animation Properties
|
||||
|
||||
```js
|
||||
animation.duration // Total duration in seconds
|
||||
animation.fps // Frames per second
|
||||
animation.frames // Total frame count
|
||||
animation.width // Animation width
|
||||
animation.height // Animation height
|
||||
animation.version // Lottie format version
|
||||
```
|
||||
|
||||
### Playback Control
|
||||
|
||||
```js
|
||||
animation.seekFrame(30) // Seek to frame 30
|
||||
animation.seek(1.5) // Seek to 1.5 seconds
|
||||
```
|
||||
|
||||
### Render to Canvas
|
||||
|
||||
```js
|
||||
const { createCanvas, LottieAnimation } = require('@napi-rs/canvas')
|
||||
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
const canvas = createCanvas(animation.width, animation.height)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
// Render at original size
|
||||
animation.render(ctx)
|
||||
|
||||
// Render with custom destination rect
|
||||
animation.render(ctx, { x: 0, y: 0, width: 800, height: 600 })
|
||||
```
|
||||
|
||||
### Supported Features
|
||||
|
||||
- **Embedded images** - Base64-encoded images (`data:image/png;base64,...`)
|
||||
- **Embedded fonts** - Vector glyph paths for text rendering without system fonts
|
||||
- **External assets** - Load images from `resourcePath` directory
|
||||
- **dotLottie format** - Extract `.lottie` ZIP files at runtime (see example)
|
||||
|
||||
### Example: Encode Lottie to Video
|
||||
|
||||
See [`example/lottie-to-video.ts`](./example/lottie-to-video.ts) for encoding Lottie animations to MP4 using [`@napi-rs/webcodecs`](https://github.com/Brooooooklyn/webcodecs-node).
|
||||
|
||||
```js
|
||||
import { createCanvas, LottieAnimation } from '@napi-rs/canvas'
|
||||
import {
|
||||
VideoEncoder,
|
||||
VideoFrame,
|
||||
Mp4Muxer,
|
||||
type EncodedVideoChunk,
|
||||
type EncodedVideoChunkMetadata,
|
||||
} from '@napi-rs/webcodecs'
|
||||
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
const canvas = createCanvas(animation.width, animation.height)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
for (let frame = 0; frame < animation.frames; frame++) {
|
||||
animation.seekFrame(frame)
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||
animation.render(ctx)
|
||||
// Encode frame to video...
|
||||
}
|
||||
```
|
||||
|
||||
# [Example](./example/tiger.js)
|
||||
|
||||
> The tiger.json was serialized from [gojs/samples/tiger](https://github.com/NorthwoodsSoftware/GoJS/blob/master/samples/tiger.html)
|
||||
|
||||
<img width="500" src="example/tiger.png">
|
||||
|
||||
```shell
|
||||
node example/anime-girl.js
|
||||
```
|
||||
|
||||
| SVG | PNG |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| <img width="500" src="example/anime-girl.svg"><br/>[CC-BY-SA 3.0](https://creativecommons.org/licenses/by/3.0) by [Niabot](https://commons.wikimedia.org/wiki/User:Niabot) | <img width="500" src="example/anime-girl.png"><br/>[CC-BY-SA 3.0](https://creativecommons.org/licenses/by/3.0) by [Niabot](https://commons.wikimedia.org/wiki/User:Niabot) |
|
||||
|
||||
# Building
|
||||
|
||||
## Build skia from source
|
||||
|
||||
You can build this project from source, the system requirements are here: https://skia.org/docs/user/build
|
||||
|
||||
```sh
|
||||
# Clone the code:
|
||||
$ git clone --recurse-submodules https://github.com/Brooooooklyn/canvas.git
|
||||
$ cd canvas
|
||||
|
||||
# Build Skia:
|
||||
$ node scripts/build-skia.js
|
||||
|
||||
# Install NPM packages, build the Node.js addon:
|
||||
$ npm install -g yarn
|
||||
$ yarn install --mode=skip-build # `canvas` (node-canvas) is a native module that only the node-canvas compat tests use and is hard to install, you can skip building it by specifying `--mode=skip-build`
|
||||
$ sudo dnf install clang # https://fedora.pkgs.org/34/fedora-x86_64/clang-12.0.0-0.3.rc1.fc34.x86_64.rpm.html
|
||||
$ yarn build
|
||||
|
||||
# All done! Run test cases or examples now:
|
||||
$ yarn test
|
||||
$ node example/tiger.js
|
||||
```
|
||||
|
||||
## Pull pre-build skia binary from GitHub
|
||||
|
||||
You can pull skia pre-build binaries if you just care the `Rust` part:
|
||||
|
||||
```sh
|
||||
# Clone the code:
|
||||
$ git clone --recurse-submodules https://github.com/Brooooooklyn/canvas.git
|
||||
$ cd canvas
|
||||
|
||||
# Download Skia binaries:
|
||||
# It will pull the binaries match the git hash in `./skia` submodule
|
||||
$ node scripts/release-skia-binary.mjs --download
|
||||
|
||||
# Install NPM packages, build the Node.js addon:
|
||||
$ npm install -g yarn
|
||||
$ yarn install --mode=skip-build
|
||||
$ sudo dnf install clang # https://fedora.pkgs.org/34/fedora-x86_64/clang-12.0.0-0.3.rc1.fc34.x86_64.rpm.html
|
||||
$ yarn build
|
||||
|
||||
# All done! Run test cases or examples now:
|
||||
$ yarn test
|
||||
$ node example/tiger.js
|
||||
```
|
||||
+1006
File diff suppressed because it is too large.
Load diff
+1461
File diff suppressed because it is too large.
Load diff
+761
@@ -0,0 +1,761 @@
|
||||
const { platform, homedir } = require('os')
|
||||
const { join } = require('path')
|
||||
|
||||
const {
|
||||
clearAllCache,
|
||||
CanvasRenderingContext2D,
|
||||
CanvasElement,
|
||||
CanvasGradient,
|
||||
CanvasPattern,
|
||||
SVGCanvas,
|
||||
Path: Path2D,
|
||||
ImageData: NativeImageData,
|
||||
Image,
|
||||
FontKey,
|
||||
GlobalFonts,
|
||||
PathOp,
|
||||
FillType,
|
||||
StrokeJoin,
|
||||
StrokeCap,
|
||||
convertSVGTextToPath,
|
||||
PdfDocument,
|
||||
GifEncoder,
|
||||
GifDisposal,
|
||||
LottieAnimation,
|
||||
TextMetrics,
|
||||
_argumentCounts,
|
||||
_imageDataConstructor,
|
||||
_toNumber: toNumber,
|
||||
setTextRenderer,
|
||||
getTextRenderer,
|
||||
} = require('./js-binding')
|
||||
|
||||
const { DOMPoint, DOMMatrix, DOMRect } = require('./geometry')
|
||||
|
||||
const loadImage = require('./load-image')
|
||||
|
||||
// Add Symbol.dispose support for GifEncoder (ECMAScript 2024 Explicit Resource Management)
|
||||
if (GifEncoder && typeof Symbol.dispose !== 'undefined') {
|
||||
GifEncoder.prototype[Symbol.dispose] = function () {
|
||||
this.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
// napi-rs defines a class's accessors in name order. Chrome's TextMetrics
|
||||
// prototype has them in IDL order (text_metrics.idl), which for...in shows,
|
||||
// then the constructor: define them again in that order.
|
||||
for (const name of [
|
||||
'width',
|
||||
'actualBoundingBoxLeft',
|
||||
'actualBoundingBoxRight',
|
||||
'fontBoundingBoxAscent',
|
||||
'fontBoundingBoxDescent',
|
||||
'actualBoundingBoxAscent',
|
||||
'actualBoundingBoxDescent',
|
||||
'hangingBaseline',
|
||||
'alphabeticBaseline',
|
||||
'ideographicBaseline',
|
||||
'emHeightAscent',
|
||||
'emHeightDescent',
|
||||
'constructor',
|
||||
]) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(TextMetrics.prototype, name)
|
||||
delete TextMetrics.prototype[name]
|
||||
Object.defineProperty(TextMetrics.prototype, name, descriptor)
|
||||
}
|
||||
|
||||
// Chrome's Symbol.toStringTag, an own property of each prototype. The
|
||||
// canvas and Image classes take their HTML element names; SVGCanvas has no
|
||||
// counterpart and no tag.
|
||||
for (const [Class, tag] of [
|
||||
[CanvasRenderingContext2D, 'CanvasRenderingContext2D'],
|
||||
[CanvasGradient, 'CanvasGradient'],
|
||||
[CanvasPattern, 'CanvasPattern'],
|
||||
[Path2D, 'Path2D'],
|
||||
[NativeImageData, 'ImageData'],
|
||||
[TextMetrics, 'TextMetrics'],
|
||||
[CanvasElement, 'HTMLCanvasElement'],
|
||||
[Image, 'HTMLImageElement'],
|
||||
]) {
|
||||
Object.defineProperty(Class.prototype, Symbol.toStringTag, { value: tag, configurable: true })
|
||||
}
|
||||
|
||||
const SvgExportFlag = {
|
||||
ConvertTextToPaths: 0x01,
|
||||
NoPrettyXML: 0x02,
|
||||
RelativePathEncoding: 0x04,
|
||||
}
|
||||
|
||||
const PngFilter = {
|
||||
None: 0x08,
|
||||
Sub: 0x10,
|
||||
Up: 0x20,
|
||||
Avg: 0x40,
|
||||
Paeth: 0x80,
|
||||
All: 0xf8,
|
||||
}
|
||||
|
||||
if (!('families' in GlobalFonts)) {
|
||||
Object.defineProperty(GlobalFonts, 'families', {
|
||||
get: function () {
|
||||
return JSON.parse(GlobalFonts.getFamilies().toString())
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!('has' in GlobalFonts)) {
|
||||
Object.defineProperty(GlobalFonts, 'has', {
|
||||
value: function has(name) {
|
||||
return !!JSON.parse(GlobalFonts.getFamilies().toString()).find(({ family }) => family === name)
|
||||
},
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
})
|
||||
}
|
||||
|
||||
// Re-evaluating this module (Jest resets its module registry per test
|
||||
// file; the .node binding and its prototypes stay loaded) must wrap the
|
||||
// native methods again, not the previous wrappers: their argument padding
|
||||
// would corrupt the argument count the native methods read.
|
||||
const NATIVE_METHODS = Symbol.for('@napi-rs/canvas:native-methods')
|
||||
function nativeMethods(proto) {
|
||||
let stash = proto[NATIVE_METHODS]
|
||||
if (stash === undefined) {
|
||||
stash = {}
|
||||
Object.defineProperty(proto, NATIVE_METHODS, { value: stash })
|
||||
}
|
||||
return stash
|
||||
}
|
||||
|
||||
const canvasNative = nativeMethods(CanvasElement.prototype)
|
||||
const _toBlob = (canvasNative.toBlob ??= CanvasElement.prototype.toBlob)
|
||||
const _convertToBlob = (canvasNative.convertToBlob ??= CanvasElement.prototype.convertToBlob)
|
||||
// A native method of CanvasElement for the receiver check: with no arguments
|
||||
// it has no side effects.
|
||||
const canvasBrand = (canvasNative.getContext ??= CanvasElement.prototype.getContext)
|
||||
if ('Blob' in globalThis) {
|
||||
// toBlob(callback, type, quality), as Chrome: the receiver, the argument
|
||||
// count and the callback are checked first, then the native method converts
|
||||
// the type and encodes. The callback gets the Blob, or null without pixels
|
||||
// or when the encoder fails, from a task. A throw in it is an uncaught
|
||||
// exception, as in Chrome (window.onerror).
|
||||
CanvasElement.prototype.toBlob = function toBlob(callback) {
|
||||
if (arguments.length < 1) {
|
||||
argumentCountError(canvasBrand, this, 'toBlob', 'HTMLCanvasElement', 1, 0)
|
||||
}
|
||||
if (typeof callback !== 'function') {
|
||||
bindingTypeError(canvasBrand, this, 'toBlob', 'HTMLCanvasElement', "parameter 1 is not of type 'Function'.")
|
||||
}
|
||||
// Only the arguments that were passed: past arguments.length,
|
||||
// arguments[i] reads Object.prototype[i], which Chrome never reads.
|
||||
const type = arguments.length > 1 ? arguments[1] : undefined
|
||||
const quality = arguments.length > 2 ? arguments[2] : undefined
|
||||
_toBlob.call(this, type, quality).then(
|
||||
(result) => {
|
||||
const blob = result === null ? null : new Blob([result.data], { type: result.type })
|
||||
queueMicrotask(() => callback(blob))
|
||||
},
|
||||
() => queueMicrotask(() => callback(null)),
|
||||
)
|
||||
}
|
||||
// convertToBlob(options): Chrome's OffscreenCanvas method. An options error
|
||||
// rejects the promise, as a WebIDL conversion error of a promise method.
|
||||
CanvasElement.prototype.convertToBlob = function convertToBlob() {
|
||||
let pending
|
||||
try {
|
||||
pending = _convertToBlob.call(this, arguments.length > 0 ? arguments[0] : undefined)
|
||||
} catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
return pending.then((result) => new Blob([result.data], { type: result.type }))
|
||||
}
|
||||
} else {
|
||||
// oxlint-disable-next-line no-unused-vars
|
||||
CanvasElement.prototype.toBlob = function toBlob(callback, mimeType, quality) {
|
||||
callback(null)
|
||||
}
|
||||
// oxlint-disable-next-line no-unused-vars
|
||||
CanvasElement.prototype.convertToBlob = function convertToBlob(options) {
|
||||
return Promise.reject(new Error('Blob is not supported in this environment'))
|
||||
}
|
||||
}
|
||||
|
||||
const ctxNative = nativeMethods(CanvasRenderingContext2D.prototype)
|
||||
const _getTransform = (ctxNative.getTransform ??= CanvasRenderingContext2D.prototype.getTransform)
|
||||
|
||||
CanvasRenderingContext2D.prototype.getTransform = function getTransform() {
|
||||
const transform = _getTransform.apply(this, arguments)
|
||||
// monkey patched, skip
|
||||
if (transform instanceof DOMMatrix) {
|
||||
return transform
|
||||
}
|
||||
const { a, b, c, d, e, f } = transform
|
||||
return new DOMMatrix([a, b, c, d, e, f])
|
||||
}
|
||||
|
||||
// Chrome checks the receiver ('Illegal invocation'), then the argument count,
|
||||
// before it converts any argument. `brand` is a native method of the class: a
|
||||
// call on another receiver throws 'Illegal invocation'. As Blink's binding
|
||||
// errors, the stack keeps the bare message and `message` gets the prefix, as
|
||||
// an enumerable own property.
|
||||
function argumentCountError(brand, self, method, iface, required, present) {
|
||||
brand.call(self)
|
||||
const message = `${required} argument${required === 1 ? '' : 's'} required, but only ${present} present.`
|
||||
const error = new TypeError(message)
|
||||
void error.stack
|
||||
Object.defineProperty(error, 'message', {
|
||||
value: `Failed to execute '${method}' on '${iface}': ${message}`,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
})
|
||||
throw error
|
||||
}
|
||||
|
||||
// A TypeError as Blink's bindings throw it after the receiver check, with the
|
||||
// message formatted as argumentCountError does.
|
||||
function bindingTypeError(brand, self, method, iface, message) {
|
||||
brand.call(self)
|
||||
const error = new TypeError(message)
|
||||
void error.stack
|
||||
Object.defineProperty(error, 'message', {
|
||||
value: `Failed to execute '${method}' on '${iface}': ${message}`,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
})
|
||||
throw error
|
||||
}
|
||||
|
||||
// Wraps `proto[method]` with Chrome's argument count check; the wrapper's
|
||||
// `length` is the required argument count, as Chrome's Function.length.
|
||||
// napi pads missing arguments with undefined, so the native method cannot
|
||||
// tell f(1) from f(1, undefined); an explicit undefined counts in Chrome.
|
||||
function requireArguments(proto, brand, iface, method, required) {
|
||||
const stash = nativeMethods(proto)
|
||||
const native = (stash[method] ??= proto[method])
|
||||
const wrapper = {
|
||||
[method]() {
|
||||
if (arguments.length < required) {
|
||||
argumentCountError(brand, this, method, iface, required, arguments.length)
|
||||
}
|
||||
return native.apply(this, arguments)
|
||||
},
|
||||
}[method]
|
||||
Object.defineProperty(wrapper, 'length', { value: required })
|
||||
proto[method] = wrapper
|
||||
}
|
||||
|
||||
const ctxBrand = CanvasRenderingContext2D.prototype.getContextAttributes
|
||||
for (const [method, required] of [
|
||||
['arc', 5],
|
||||
['arcTo', 5],
|
||||
['bezierCurveTo', 6],
|
||||
['clearRect', 4],
|
||||
['createConicGradient', 3],
|
||||
['createLinearGradient', 4],
|
||||
['createRadialGradient', 6],
|
||||
['ellipse', 7],
|
||||
['fillRect', 4],
|
||||
['fillText', 3],
|
||||
['getImageData', 4],
|
||||
['lineTo', 2],
|
||||
['measureText', 1],
|
||||
['moveTo', 2],
|
||||
['quadraticCurveTo', 4],
|
||||
['rect', 4],
|
||||
['rotate', 1],
|
||||
['roundRect', 4],
|
||||
['scale', 2],
|
||||
['setLineDash', 1],
|
||||
['strokeRect', 4],
|
||||
['strokeText', 3],
|
||||
['transform', 6],
|
||||
['translate', 2],
|
||||
]) {
|
||||
requireArguments(CanvasRenderingContext2D.prototype, ctxBrand, 'CanvasRenderingContext2D', method, required)
|
||||
}
|
||||
|
||||
// getContext(contextId, options): Chrome needs the id. The native method is
|
||||
// its own brand: with no arguments it converts undefined to 'undefined' and
|
||||
// returns null, without side effects.
|
||||
for (const [Class, iface] of [
|
||||
[CanvasElement, 'HTMLCanvasElement'],
|
||||
[SVGCanvas, 'SVGCanvas'],
|
||||
]) {
|
||||
const stash = nativeMethods(Class.prototype)
|
||||
requireArguments(Class.prototype, (stash.getContext ??= Class.prototype.getContext), iface, 'getContext', 1)
|
||||
}
|
||||
|
||||
const pathBrand = Path2D.prototype.getFillType
|
||||
for (const [method, required] of [
|
||||
['arc', 5],
|
||||
['arcTo', 5],
|
||||
['bezierCurveTo', 6],
|
||||
['ellipse', 7],
|
||||
['lineTo', 2],
|
||||
['moveTo', 2],
|
||||
['quadraticCurveTo', 4],
|
||||
['rect', 4],
|
||||
['roundRect', 4],
|
||||
]) {
|
||||
requireArguments(Path2D.prototype, pathBrand, 'Path2D', method, required)
|
||||
}
|
||||
|
||||
// The argument-count markers for 0 to 9 arguments. napi pads missing
|
||||
// arguments with undefined, so the wrappers below pass the real count after
|
||||
// the positional arguments, as one of these markers: the native methods read
|
||||
// a count only from a marker, and any other value there (from a raw
|
||||
// js-binding call) is an extra argument.
|
||||
const ARGUMENT_COUNTS = _argumentCounts()
|
||||
|
||||
// new ImageData(): Chrome checks `new` and the real argument count before it
|
||||
// picks an overload (image_data.idl). The class napi-rs makes sees neither,
|
||||
// so a native function checks them and builds the instance itself, from
|
||||
// new.target.prototype. Instances share the class prototype, so instanceof
|
||||
// works for those that createImageData and getImageData return.
|
||||
const ImageData = _imageDataConstructor()
|
||||
Object.defineProperty(ImageData, 'length', { value: 2 })
|
||||
Object.defineProperty(ImageData, 'prototype', { value: NativeImageData.prototype, writable: false })
|
||||
Object.defineProperty(NativeImageData.prototype, 'constructor', {
|
||||
value: ImageData,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
// What the wrappers below pass after their `n` positional arguments, for a
|
||||
// call with `count` (1 to `n`) of them, the last one `last`. Without a marker
|
||||
// the native method counts up to the last argument that is not undefined:
|
||||
// that is `count` unless `last` is an explicit undefined, and only then is
|
||||
// the marker needed.
|
||||
function argumentCount(count, last) {
|
||||
return last === undefined ? ARGUMENT_COUNTS[count] : undefined
|
||||
}
|
||||
|
||||
// fill(), clip(), stroke(), isPointInPath() and isPointInStroke(): WebIDL
|
||||
// picks the overload from the argument count (canvas_2d_recorder_context.idl),
|
||||
// and an explicit undefined counts: fill(path, undefined) is the nonzero
|
||||
// fill of path, fill(undefined, 'evenodd') a TypeError.
|
||||
// These wrappers and drawImage's read only the arguments the call has: past
|
||||
// arguments.length, arguments[i] would read Object.prototype[i], which
|
||||
// Chrome never reads.
|
||||
const _fill = (ctxNative.fill ??= CanvasRenderingContext2D.prototype.fill)
|
||||
CanvasRenderingContext2D.prototype.fill = function fill() {
|
||||
const count = Math.min(arguments.length, 2)
|
||||
return _fill.call(
|
||||
this,
|
||||
count > 0 ? arguments[0] : undefined,
|
||||
count > 1 ? arguments[1] : undefined,
|
||||
count === 0 ? undefined : argumentCount(count, arguments[count - 1]),
|
||||
)
|
||||
}
|
||||
|
||||
const _clip = (ctxNative.clip ??= CanvasRenderingContext2D.prototype.clip)
|
||||
CanvasRenderingContext2D.prototype.clip = function clip() {
|
||||
const count = Math.min(arguments.length, 2)
|
||||
return _clip.call(
|
||||
this,
|
||||
count > 0 ? arguments[0] : undefined,
|
||||
count > 1 ? arguments[1] : undefined,
|
||||
count === 0 ? undefined : argumentCount(count, arguments[count - 1]),
|
||||
)
|
||||
}
|
||||
|
||||
const _stroke = (ctxNative.stroke ??= CanvasRenderingContext2D.prototype.stroke)
|
||||
CanvasRenderingContext2D.prototype.stroke = function stroke() {
|
||||
if (arguments.length === 0) {
|
||||
return _stroke.call(this, undefined, undefined)
|
||||
}
|
||||
const path = arguments[0]
|
||||
return _stroke.call(this, path, argumentCount(1, path))
|
||||
}
|
||||
|
||||
const _isPointInPath = (ctxNative.isPointInPath ??= CanvasRenderingContext2D.prototype.isPointInPath)
|
||||
CanvasRenderingContext2D.prototype.isPointInPath = function isPointInPath() {
|
||||
if (arguments.length < 2) {
|
||||
argumentCountError(ctxBrand, this, 'isPointInPath', 'CanvasRenderingContext2D', 2, arguments.length)
|
||||
}
|
||||
const count = Math.min(arguments.length, 4)
|
||||
return _isPointInPath.call(
|
||||
this,
|
||||
arguments[0],
|
||||
arguments[1],
|
||||
count > 2 ? arguments[2] : undefined,
|
||||
count > 3 ? arguments[3] : undefined,
|
||||
// (x, y, undefined) converts as (x, y) when x is not an object (only an
|
||||
// object can be a Path2D), so the count is not needed.
|
||||
count === 3 && typeof arguments[0] !== 'object' ? undefined : argumentCount(count, arguments[count - 1]),
|
||||
)
|
||||
}
|
||||
Object.defineProperty(CanvasRenderingContext2D.prototype.isPointInPath, 'length', { value: 2 })
|
||||
|
||||
const _isPointInStroke = (ctxNative.isPointInStroke ??= CanvasRenderingContext2D.prototype.isPointInStroke)
|
||||
CanvasRenderingContext2D.prototype.isPointInStroke = function isPointInStroke() {
|
||||
if (arguments.length < 2) {
|
||||
argumentCountError(ctxBrand, this, 'isPointInStroke', 'CanvasRenderingContext2D', 2, arguments.length)
|
||||
}
|
||||
const count = Math.min(arguments.length, 3)
|
||||
return _isPointInStroke.call(
|
||||
this,
|
||||
arguments[0],
|
||||
arguments[1],
|
||||
count > 2 ? arguments[2] : undefined,
|
||||
argumentCount(count, arguments[count - 1]),
|
||||
)
|
||||
}
|
||||
Object.defineProperty(CanvasRenderingContext2D.prototype.isPointInStroke, 'length', { value: 2 })
|
||||
|
||||
// A TypeError as Chrome's bindings throw it, as in argumentCountError: the
|
||||
// stack keeps the bare message, and `message` gets the prefix.
|
||||
function contextTypeError(prefix, message) {
|
||||
const error = new TypeError(message)
|
||||
void error.stack
|
||||
Object.defineProperty(error, 'message', {
|
||||
value: prefix + message,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
})
|
||||
return error
|
||||
}
|
||||
|
||||
// An `unrestricted double` member of a matrix dictionary; undefined when it
|
||||
// is absent. The native ToNumber keeps the engine's texts, and the error
|
||||
// names the member, as in Chrome.
|
||||
function matrixMember(value, key, dictionary, prefix) {
|
||||
if (typeof value === 'number' || value === undefined) return value
|
||||
return toNumber(value, `${prefix}Failed to read the '${key}' property from '${dictionary}': `)
|
||||
}
|
||||
|
||||
// a and m11 (and so on) disagree: both given and not equal. Two NaNs agree.
|
||||
const mismatch = (x, y) => x !== undefined && y !== undefined && x !== y && (x === x || y === y)
|
||||
// A 3D member against its identity value; absent is the identity. As C++
|
||||
// truthiness, NaN counts as 3D and -0 as 0.
|
||||
const notZero = (v) => v !== undefined && v !== 0
|
||||
const notOne = (v) => v !== undefined && v !== 1
|
||||
|
||||
// The matrix of a DOMMatrix2DInit, or of a DOMMatrixInit when `full`, as
|
||||
// [m11, m12, m21, m22, m41, m42]; undefined and null are {}. As Blink's
|
||||
// bindings, every member is read with [[Get]], in order (a..f, m11, m12,
|
||||
// m21, m22, m41, m42, then is2D and m13..m44), then checked as
|
||||
// DOMMatrixReadOnly::ValidateAndFixup (dom_matrix_read_only.cc). A DOMMatrix
|
||||
// is read the same way: an own property, a patched getter or a Proxy may
|
||||
// make its members disagree. The result is one shared array: read it before
|
||||
// any other user code runs.
|
||||
const MATRIX = [1, 0, 0, 1, 0, 0]
|
||||
function matrix2DFromInit(init, prefix, full) {
|
||||
if (init === undefined || init === null) {
|
||||
MATRIX[0] = 1
|
||||
MATRIX[1] = 0
|
||||
MATRIX[2] = 0
|
||||
MATRIX[3] = 1
|
||||
MATRIX[4] = 0
|
||||
MATRIX[5] = 0
|
||||
return MATRIX
|
||||
}
|
||||
if (typeof init !== 'object' && typeof init !== 'function') {
|
||||
throw contextTypeError(prefix, `The provided value is not of type '${full ? 'DOMMatrixInit' : 'DOMMatrix2DInit'}'.`)
|
||||
}
|
||||
const D2 = 'DOMMatrix2DInit'
|
||||
const a = matrixMember(init.a, 'a', D2, prefix)
|
||||
const b = matrixMember(init.b, 'b', D2, prefix)
|
||||
const c = matrixMember(init.c, 'c', D2, prefix)
|
||||
const d = matrixMember(init.d, 'd', D2, prefix)
|
||||
const e = matrixMember(init.e, 'e', D2, prefix)
|
||||
const f = matrixMember(init.f, 'f', D2, prefix)
|
||||
const m11 = matrixMember(init.m11, 'm11', D2, prefix)
|
||||
const m12 = matrixMember(init.m12, 'm12', D2, prefix)
|
||||
const m21 = matrixMember(init.m21, 'm21', D2, prefix)
|
||||
const m22 = matrixMember(init.m22, 'm22', D2, prefix)
|
||||
const m41 = matrixMember(init.m41, 'm41', D2, prefix)
|
||||
const m42 = matrixMember(init.m42, 'm42', D2, prefix)
|
||||
let is3DIn2D = false
|
||||
if (full) {
|
||||
const D = 'DOMMatrixInit'
|
||||
const is2D = init.is2D
|
||||
const m13 = matrixMember(init.m13, 'm13', D, prefix)
|
||||
const m14 = matrixMember(init.m14, 'm14', D, prefix)
|
||||
const m23 = matrixMember(init.m23, 'm23', D, prefix)
|
||||
const m24 = matrixMember(init.m24, 'm24', D, prefix)
|
||||
const m31 = matrixMember(init.m31, 'm31', D, prefix)
|
||||
const m32 = matrixMember(init.m32, 'm32', D, prefix)
|
||||
const m33 = matrixMember(init.m33, 'm33', D, prefix)
|
||||
const m34 = matrixMember(init.m34, 'm34', D, prefix)
|
||||
const m43 = matrixMember(init.m43, 'm43', D, prefix)
|
||||
const m44 = matrixMember(init.m44, 'm44', D, prefix)
|
||||
// is2D is a boolean member: ToBoolean when present.
|
||||
is3DIn2D =
|
||||
is2D !== undefined &&
|
||||
!!is2D &&
|
||||
(notZero(m31) ||
|
||||
notZero(m32) ||
|
||||
notZero(m13) ||
|
||||
notZero(m23) ||
|
||||
notZero(m43) ||
|
||||
notZero(m14) ||
|
||||
notZero(m24) ||
|
||||
notZero(m34) ||
|
||||
notOne(m33) ||
|
||||
notOne(m44))
|
||||
}
|
||||
if (
|
||||
mismatch(a, m11) ||
|
||||
mismatch(b, m12) ||
|
||||
mismatch(c, m21) ||
|
||||
mismatch(d, m22) ||
|
||||
mismatch(e, m41) ||
|
||||
mismatch(f, m42)
|
||||
) {
|
||||
throw contextTypeError(prefix, 'Property mismatch on matrix initialization.')
|
||||
}
|
||||
if (is3DIn2D) {
|
||||
throw contextTypeError(prefix, 'The is2D member is set to true but the input matrix is a 3d matrix.')
|
||||
}
|
||||
MATRIX[0] = m11 !== undefined ? m11 : a !== undefined ? a : 1
|
||||
MATRIX[1] = m12 !== undefined ? m12 : b !== undefined ? b : 0
|
||||
MATRIX[2] = m21 !== undefined ? m21 : c !== undefined ? c : 0
|
||||
MATRIX[3] = m22 !== undefined ? m22 : d !== undefined ? d : 1
|
||||
MATRIX[4] = m41 !== undefined ? m41 : e !== undefined ? e : 0
|
||||
MATRIX[5] = m42 !== undefined ? m42 : f !== undefined ? f : 0
|
||||
return MATRIX
|
||||
}
|
||||
|
||||
// setTransform(): six or more arguments are six numbers, fewer a DOMMatrixInit
|
||||
// (canvas_2d_recorder_context.idl), and an explicit undefined counts. The
|
||||
// DOMMatrixInit is read above; the native method takes six numbers. It reads
|
||||
// a first argument that is not a number as a DOMMatrixInit, the form a raw
|
||||
// js-binding call may use, so ToNumber runs here for such an `a`.
|
||||
const _setTransform = (ctxNative.setTransform ??= CanvasRenderingContext2D.prototype.setTransform)
|
||||
// A cheap native method: on another receiver it throws 'Illegal invocation',
|
||||
// which Chrome checks before it converts any argument.
|
||||
const ctxReceiver = CanvasRenderingContext2D.prototype.isContextLost
|
||||
const SET_TRANSFORM = "Failed to execute 'setTransform' on 'CanvasRenderingContext2D': "
|
||||
CanvasRenderingContext2D.prototype.setTransform = function setTransform() {
|
||||
if (arguments.length >= 6) {
|
||||
let a = arguments[0]
|
||||
if (typeof a !== 'number') {
|
||||
ctxReceiver.call(this)
|
||||
a = toNumber(a, SET_TRANSFORM)
|
||||
}
|
||||
return _setTransform.call(this, a, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5])
|
||||
}
|
||||
// Past arguments.length, arguments[0] would read Object.prototype[0].
|
||||
const init = arguments.length > 0 ? arguments[0] : undefined
|
||||
if (init !== undefined && init !== null) ctxReceiver.call(this)
|
||||
const m = matrix2DFromInit(init, SET_TRANSFORM, true)
|
||||
return _setTransform.call(this, m[0], m[1], m[2], m[3], m[4], m[5])
|
||||
}
|
||||
|
||||
// addPath(path, transform = {}): Chrome checks the receiver, the argument
|
||||
// count and the path, then reads the DOMMatrix2DInit, read above. The native
|
||||
// method takes six numbers after the path; anything else there is a
|
||||
// DOMMatrix2DInit, which only a raw js-binding call passes. Without a
|
||||
// transform (undefined or null is `{}`), a native method that takes only the
|
||||
// path adds it as it is; Chrome's Path2D has no such method, so it comes off
|
||||
// the prototype.
|
||||
const pathNative = nativeMethods(Path2D.prototype)
|
||||
const _addPath = (pathNative.addPath ??= Path2D.prototype.addPath)
|
||||
const _addPathWithoutTransform = (pathNative._addPathWithoutTransform ??= Path2D.prototype._addPathWithoutTransform)
|
||||
delete Path2D.prototype._addPathWithoutTransform
|
||||
const ADD_PATH = "Failed to execute 'addPath' on 'Path2D': "
|
||||
Path2D.prototype.addPath = function addPath() {
|
||||
if (arguments.length < 1) {
|
||||
argumentCountError(pathBrand, this, 'addPath', 'Path2D', 1, arguments.length)
|
||||
}
|
||||
const path = arguments[0]
|
||||
// Past arguments.length, arguments[1] would read Object.prototype[1].
|
||||
const transform = arguments.length > 1 ? arguments[1] : undefined
|
||||
if (transform === undefined || transform === null) {
|
||||
return _addPathWithoutTransform.call(this, path)
|
||||
}
|
||||
pathBrand.call(this)
|
||||
try {
|
||||
pathBrand.call(path)
|
||||
} catch {
|
||||
throw contextTypeError(ADD_PATH, "parameter 1 is not of type 'Path2D'.")
|
||||
}
|
||||
const m = matrix2DFromInit(transform, ADD_PATH, false)
|
||||
return _addPath.call(this, path, m[0], m[1], m[2], m[3], m[4], m[5])
|
||||
}
|
||||
Object.defineProperty(Path2D.prototype.addPath, 'length', { value: 1 })
|
||||
|
||||
// createImageData(): WebIDL picks the overload from the argument count, and an
|
||||
// explicit undefined counts: createImageData(imagedata, undefined) is the
|
||||
// (sw, sh) form.
|
||||
const _createImageData = (ctxNative.createImageData ??= CanvasRenderingContext2D.prototype.createImageData)
|
||||
|
||||
CanvasRenderingContext2D.prototype.createImageData = function createImageData() {
|
||||
const count = arguments.length
|
||||
// Past arguments.length, arguments[i] would read Object.prototype[i]: pass
|
||||
// undefined there, as napi pads missing arguments.
|
||||
return _createImageData.call(
|
||||
this,
|
||||
count > 0 ? arguments[0] : undefined,
|
||||
count > 1 ? arguments[1] : undefined,
|
||||
count > 2 ? arguments[2] : undefined,
|
||||
count > 3 ? arguments[3] : undefined,
|
||||
ARGUMENT_COUNTS[Math.min(count, 4)],
|
||||
)
|
||||
}
|
||||
Object.defineProperty(CanvasRenderingContext2D.prototype.createImageData, 'length', { value: 1 })
|
||||
|
||||
// putImageData(imagedata, dx, dy) or (imagedata, dx, dy, dirtyX, dirtyY,
|
||||
// dirtyWidth, dirtyHeight): as in Chrome, it needs 3 arguments; the native
|
||||
// method picks the overload from the argument count (3 or 7).
|
||||
const _putImageData = (ctxNative.putImageData ??= CanvasRenderingContext2D.prototype.putImageData)
|
||||
|
||||
CanvasRenderingContext2D.prototype.putImageData = function putImageData() {
|
||||
const count = arguments.length
|
||||
if (count < 3) {
|
||||
argumentCountError(ctxBrand, this, 'putImageData', 'CanvasRenderingContext2D', 3, count)
|
||||
}
|
||||
// Past arguments.length, arguments[i] would read Object.prototype[i]: pass
|
||||
// undefined there, as napi pads missing arguments.
|
||||
return _putImageData.call(
|
||||
this,
|
||||
arguments[0],
|
||||
arguments[1],
|
||||
arguments[2],
|
||||
count > 3 ? arguments[3] : undefined,
|
||||
count > 4 ? arguments[4] : undefined,
|
||||
count > 5 ? arguments[5] : undefined,
|
||||
count > 6 ? arguments[6] : undefined,
|
||||
ARGUMENT_COUNTS[Math.min(count, 7)],
|
||||
)
|
||||
}
|
||||
Object.defineProperty(CanvasRenderingContext2D.prototype.putImageData, 'length', { value: 3 })
|
||||
|
||||
// createPattern(image, repetitionType): as in Chrome, both arguments are
|
||||
// required, and the image is converted before the repetition, a
|
||||
// [LegacyNullToEmptyString] DOMString (canvas_2d_recorder_context.idl), so
|
||||
// null is '' and undefined is 'undefined'.
|
||||
const _createPattern = (ctxNative.createPattern ??= CanvasRenderingContext2D.prototype.createPattern)
|
||||
|
||||
CanvasRenderingContext2D.prototype.createPattern = function createPattern(image, repetition) {
|
||||
return _createPattern.call(this, image, repetition, ARGUMENT_COUNTS[Math.min(arguments.length, 4)])
|
||||
}
|
||||
|
||||
// addColorStop(offset, color): both arguments are required. CanvasGradient
|
||||
// has no other native method to check the receiver first, so the native
|
||||
// method itself reads the real count from the marker after them.
|
||||
const gradientNative = nativeMethods(CanvasGradient.prototype)
|
||||
const _addColorStop = (gradientNative.addColorStop ??= CanvasGradient.prototype.addColorStop)
|
||||
CanvasGradient.prototype.addColorStop = function addColorStop(offset, color) {
|
||||
return _addColorStop.call(this, offset, color, ARGUMENT_COUNTS[Math.min(arguments.length, 2)])
|
||||
}
|
||||
|
||||
// Workaround for webpack bundling issue with drawImage
|
||||
// Store the original drawImage method
|
||||
const _drawImage = (ctxNative.drawImage ??= CanvasRenderingContext2D.prototype.drawImage)
|
||||
|
||||
// Override drawImage to ensure proper type recognition in bundled environments.
|
||||
// As in Chrome, it needs 3 arguments; the native method picks the overload
|
||||
// from the argument count (3, 5 or 9).
|
||||
CanvasRenderingContext2D.prototype.drawImage = function drawImage() {
|
||||
if (arguments.length < 3) {
|
||||
argumentCountError(ctxBrand, this, 'drawImage', 'CanvasRenderingContext2D', 3, arguments.length)
|
||||
}
|
||||
let image = arguments[0]
|
||||
// If the image is a Canvas-like object but not recognized due to bundling,
|
||||
// we need to ensure it's properly identified
|
||||
if (image && typeof image === 'object') {
|
||||
// First check if it's a wrapped canvas object
|
||||
if (image.canvas instanceof CanvasElement || image.canvas instanceof SVGCanvas) {
|
||||
image = image.canvas
|
||||
} else if (image._canvas instanceof CanvasElement || image._canvas instanceof SVGCanvas) {
|
||||
image = image._canvas
|
||||
}
|
||||
// Then check if it's a Canvas-like object by checking for getContext method
|
||||
else if (typeof image.getContext === 'function' && image.width && image.height) {
|
||||
// If it has canvas properties but isn't recognized as CanvasElement or SVGCanvas,
|
||||
// try to correct the prototype chain
|
||||
if (!(image instanceof CanvasElement) && !(image instanceof SVGCanvas)) {
|
||||
// Try to create a proper CanvasElement from the canvas-like object
|
||||
// This helps when webpack has transformed the prototype chain
|
||||
Object.setPrototypeOf(image, CanvasElement.prototype)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call the original drawImage with the potentially corrected image
|
||||
const count = Math.min(arguments.length, 9)
|
||||
return _drawImage.call(
|
||||
this,
|
||||
image,
|
||||
arguments[1],
|
||||
arguments[2],
|
||||
count > 3 ? arguments[3] : undefined,
|
||||
count > 4 ? arguments[4] : undefined,
|
||||
count > 5 ? arguments[5] : undefined,
|
||||
count > 6 ? arguments[6] : undefined,
|
||||
count > 7 ? arguments[7] : undefined,
|
||||
count > 8 ? arguments[8] : undefined,
|
||||
argumentCount(count, arguments[count - 1]),
|
||||
)
|
||||
}
|
||||
Object.defineProperty(CanvasRenderingContext2D.prototype.drawImage, 'length', { value: 3 })
|
||||
|
||||
function createCanvas(width, height, flag) {
|
||||
const isSvgBackend = typeof flag !== 'undefined'
|
||||
return isSvgBackend ? new SVGCanvas(width, height, flag) : new CanvasElement(width, height)
|
||||
}
|
||||
|
||||
class Canvas {
|
||||
constructor(width, height, flag) {
|
||||
return createCanvas(width, height, flag)
|
||||
}
|
||||
|
||||
static [Symbol.hasInstance](instance) {
|
||||
return instance instanceof CanvasElement || instance instanceof SVGCanvas
|
||||
}
|
||||
}
|
||||
|
||||
if (!process.env.DISABLE_SYSTEM_FONTS_LOAD) {
|
||||
// Installed fonts and the per-user font folders: FreeType by default;
|
||||
// CoreText's on macOS after setTextRenderer('system'). On macOS that is
|
||||
// /Library/Fonts (all users) and ~/Library/Fonts, after
|
||||
// /System/Library/Fonts, as CoreText lists them.
|
||||
const homedirPath = homedir()
|
||||
const userFontDirs =
|
||||
{
|
||||
win32: [join(homedirPath, 'AppData', 'Local', 'Microsoft', 'Windows', 'Fonts')],
|
||||
darwin: ['/Library/Fonts', join(homedirPath, 'Library', 'Fonts')],
|
||||
linux: [join('usr', 'local', 'share', 'fonts'), join(homedirPath, '.fonts')],
|
||||
}[platform()] ?? []
|
||||
GlobalFonts.enableSystemFonts(userFontDirs)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
clearAllCache,
|
||||
setTextRenderer,
|
||||
getTextRenderer,
|
||||
Canvas,
|
||||
createCanvas,
|
||||
Path2D,
|
||||
ImageData,
|
||||
Image,
|
||||
PathOp,
|
||||
FillType,
|
||||
StrokeCap,
|
||||
StrokeJoin,
|
||||
SvgExportFlag,
|
||||
PngFilter,
|
||||
GlobalFonts: GlobalFonts,
|
||||
convertSVGTextToPath,
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
loadImage,
|
||||
FontKey,
|
||||
// Export these for better webpack compatibility
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
PDFDocument: PdfDocument,
|
||||
// GIF encoding
|
||||
GifEncoder,
|
||||
GifDisposal,
|
||||
// Lottie animation
|
||||
LottieAnimation,
|
||||
}
|
||||
+466
@@ -0,0 +1,466 @@
|
||||
// prettier-ignore
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
/* auto-generated by NAPI-RS */
|
||||
|
||||
const { readFileSync } = require('fs')
|
||||
let nativeBinding = null
|
||||
const loadErrors = []
|
||||
|
||||
const isMusl = () => {
|
||||
let musl = false
|
||||
if (process.platform === 'linux') {
|
||||
musl = isMuslFromFilesystem()
|
||||
if (musl === null) {
|
||||
musl = isMuslFromReport()
|
||||
}
|
||||
if (musl === null) {
|
||||
musl = isMuslFromChildProcess()
|
||||
}
|
||||
}
|
||||
return musl
|
||||
}
|
||||
|
||||
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-')
|
||||
|
||||
const isMuslFromFilesystem = () => {
|
||||
try {
|
||||
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isMuslFromReport = () => {
|
||||
let report = null
|
||||
if (typeof process.report?.getReport === 'function') {
|
||||
process.report.excludeNetwork = true
|
||||
report = process.report.getReport()
|
||||
}
|
||||
if (!report) {
|
||||
return null
|
||||
}
|
||||
if (report.header && report.header.glibcVersionRuntime) {
|
||||
return false
|
||||
}
|
||||
if (Array.isArray(report.sharedObjects)) {
|
||||
if (report.sharedObjects.some(isFileMusl)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const isMuslFromChildProcess = () => {
|
||||
try {
|
||||
return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl')
|
||||
} catch (e) {
|
||||
// If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function requireNative() {
|
||||
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
|
||||
try {
|
||||
return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH)
|
||||
} catch (err) {
|
||||
loadErrors.push(err)
|
||||
}
|
||||
} else if (process.platform === 'android') {
|
||||
if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.android-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-android-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
try {
|
||||
return require('./skia.android-arm-eabi.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-android-arm-eabi')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'win32') {
|
||||
if (process.arch === 'x64') {
|
||||
if (
|
||||
process.config?.variables?.shlib_suffix === 'dll.a' ||
|
||||
process.config?.variables?.node_target_type === 'shared_library'
|
||||
) {
|
||||
try {
|
||||
return require('./skia.win32-x64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-x64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.win32-x64-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-x64-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'ia32') {
|
||||
try {
|
||||
return require('./skia.win32-ia32-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-ia32-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.win32-arm64-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-arm64-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'darwin') {
|
||||
try {
|
||||
return require('./skia.darwin-universal.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-universal')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.darwin-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.darwin-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'freebsd') {
|
||||
if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.freebsd-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-freebsd-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.freebsd-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-freebsd-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'linux') {
|
||||
if (process.arch === 'x64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-x64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-x64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-x64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-x64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-arm64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-arm64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-arm-musleabihf.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm-musleabihf')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-arm-gnueabihf.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm-gnueabihf')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'loong64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-loong64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-loong64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-loong64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-loong64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'riscv64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-riscv64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-riscv64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-riscv64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-riscv64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'ppc64') {
|
||||
try {
|
||||
return require('./skia.linux-ppc64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-ppc64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 's390x') {
|
||||
try {
|
||||
return require('./skia.linux-s390x-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-s390x-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'openharmony') {
|
||||
if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.openharmony-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-openharmony-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.openharmony-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-openharmony-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
try {
|
||||
return require('./skia.openharmony-arm.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
const binding = require('@napi-rs/canvas-openharmony-arm')
|
||||
return binding
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`))
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`))
|
||||
}
|
||||
}
|
||||
|
||||
nativeBinding = requireNative()
|
||||
|
||||
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
|
||||
let wasiBinding = null
|
||||
let wasiBindingError = null
|
||||
try {
|
||||
wasiBinding = require('./skia.wasi.cjs')
|
||||
nativeBinding = wasiBinding
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) {
|
||||
wasiBindingError = err
|
||||
}
|
||||
}
|
||||
if (!nativeBinding) {
|
||||
try {
|
||||
wasiBinding = require('@napi-rs/canvas-wasm32-wasi')
|
||||
nativeBinding = wasiBinding
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) {
|
||||
wasiBindingError.cause = err
|
||||
loadErrors.push(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!nativeBinding) {
|
||||
if (loadErrors.length > 0) {
|
||||
throw new Error(
|
||||
`Cannot find native binding. ` +
|
||||
`npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` +
|
||||
'Please try `npm i` again after removing both package-lock.json and node_modules directory.',
|
||||
{
|
||||
cause: loadErrors.reduce((err, cur) => {
|
||||
cur.cause = err
|
||||
return cur
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
throw new Error(`Failed to load native binding`)
|
||||
}
|
||||
|
||||
module.exports = nativeBinding
|
||||
module.exports.GlobalFonts = nativeBinding.GlobalFonts
|
||||
module.exports.CanvasElement = nativeBinding.CanvasElement
|
||||
module.exports.CanvasGradient = nativeBinding.CanvasGradient
|
||||
module.exports.CanvasPattern = nativeBinding.CanvasPattern
|
||||
module.exports.CanvasRenderingContext2D = nativeBinding.CanvasRenderingContext2D
|
||||
module.exports.FontKey = nativeBinding.FontKey
|
||||
module.exports.Image = nativeBinding.Image
|
||||
module.exports.ImageData = nativeBinding.ImageData
|
||||
module.exports.Path = nativeBinding.Path
|
||||
module.exports.PdfDocument = nativeBinding.PdfDocument
|
||||
module.exports.SVGCanvas = nativeBinding.SVGCanvas
|
||||
module.exports.ChromaSubsampling = nativeBinding.ChromaSubsampling
|
||||
module.exports.clearAllCache = nativeBinding.clearAllCache
|
||||
module.exports.convertSVGTextToPath = nativeBinding.convertSVGTextToPath
|
||||
module.exports.setTextRenderer = nativeBinding.setTextRenderer
|
||||
module.exports.getTextRenderer = nativeBinding.getTextRenderer
|
||||
module.exports.FillType = nativeBinding.FillType
|
||||
module.exports.PathOp = nativeBinding.PathOp
|
||||
module.exports.StrokeCap = nativeBinding.StrokeCap
|
||||
module.exports.StrokeJoin = nativeBinding.StrokeJoin
|
||||
module.exports.SvgExportFlag = nativeBinding.SvgExportFlag
|
||||
module.exports.GifEncoder = nativeBinding.GifEncoder
|
||||
module.exports.GifDisposal = nativeBinding.GifDisposal
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
const fs = require('fs')
|
||||
const { Readable } = require('stream')
|
||||
const { URL } = require('url')
|
||||
|
||||
const { Image } = require('./js-binding')
|
||||
|
||||
let http, https
|
||||
|
||||
const MAX_REDIRECTS = 20
|
||||
// Image fires onerror with an Event, as browsers do; the Error behind it is
|
||||
// under this key.
|
||||
const IMAGE_ERROR = Symbol.for('@napi-rs/canvas/image-error')
|
||||
const REDIRECT_STATUSES = new Set([301, 302])
|
||||
|
||||
/**
|
||||
* Loads the given source into canvas Image
|
||||
* @param {string|URL|Image|Buffer} source The image source to be loaded
|
||||
* @param {object} options Options passed to the loader
|
||||
*/
|
||||
module.exports = async function loadImage(source, options = {}) {
|
||||
// use the same buffer without copying if the source is a buffer
|
||||
if (Buffer.isBuffer(source) || source instanceof Uint8Array) return createImage(source, options.alt)
|
||||
// load readable stream as image
|
||||
if (source instanceof Readable) return createImage(await consumeStream(source), options.alt)
|
||||
// construct a Uint8Array if the source is ArrayBuffer or SharedArrayBuffer
|
||||
if (source instanceof ArrayBuffer || source instanceof SharedArrayBuffer)
|
||||
return createImage(new Uint8Array(source), options.alt)
|
||||
// construct a buffer if the source is buffer-like
|
||||
if (isBufferLike(source)) return createImage(Buffer.from(source), options.alt)
|
||||
// if the source is Image instance, copy the image src to new image
|
||||
if (source instanceof Image) return createImage(source.src, options.alt)
|
||||
// A data: URL (the URL parser drops leading C0 controls and spaces) is
|
||||
// the image's src, as in a browser: Image parses it with the Fetch data:
|
||||
// URL processor. A URL object with the data: scheme too.
|
||||
// An empty body fires onerror, so the promise settles (issue #1255).
|
||||
if (typeof source === 'string' && isDataUrl(source)) return createImage(source, options.alt)
|
||||
if (source instanceof URL && source.protocol === 'data:') return createImage(source.href, options.alt)
|
||||
// if source is a string or URL instance
|
||||
if (typeof source === 'string') {
|
||||
// if the source exists as a file, construct image from that file
|
||||
if (!source.startsWith('http') && !source.startsWith('https') && (await exists(source))) {
|
||||
return createImage(source, options.alt)
|
||||
} else {
|
||||
// the source is a remote url here
|
||||
source = new URL(source)
|
||||
// attempt to download the remote source and construct image
|
||||
const data = await new Promise((resolve, reject) =>
|
||||
makeRequest(
|
||||
source,
|
||||
resolve,
|
||||
reject,
|
||||
typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
|
||||
options.requestOptions,
|
||||
),
|
||||
)
|
||||
return createImage(data, options.alt)
|
||||
}
|
||||
}
|
||||
|
||||
if (source instanceof URL) {
|
||||
if (source.protocol === 'file:') {
|
||||
// remove the leading slash on windows
|
||||
return createImage(process.platform === 'win32' ? source.pathname.substring(1) : source.pathname, options.alt)
|
||||
} else {
|
||||
const data = await new Promise((resolve, reject) =>
|
||||
makeRequest(
|
||||
source,
|
||||
resolve,
|
||||
reject,
|
||||
typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
|
||||
options.requestOptions,
|
||||
),
|
||||
)
|
||||
return createImage(data, options.alt)
|
||||
}
|
||||
}
|
||||
|
||||
// throw error as don't support that source
|
||||
throw new TypeError('unsupported image source')
|
||||
}
|
||||
|
||||
function makeRequest(url, resolve, reject, redirectCount, requestOptions) {
|
||||
const isHttps = url.protocol === 'https:'
|
||||
// lazy load the lib
|
||||
const lib = isHttps ? (!https ? (https = require('https')) : https) : !http ? (http = require('http')) : http
|
||||
|
||||
lib
|
||||
.get(url.toString(), requestOptions || {}, (res) => {
|
||||
try {
|
||||
const shouldRedirect = REDIRECT_STATUSES.has(res.statusCode) && typeof res.headers.location === 'string'
|
||||
if (shouldRedirect && redirectCount > 0)
|
||||
return makeRequest(
|
||||
new URL(res.headers.location, url.origin),
|
||||
resolve,
|
||||
reject,
|
||||
redirectCount - 1,
|
||||
requestOptions,
|
||||
)
|
||||
if (typeof res.statusCode === 'number' && (res.statusCode < 200 || res.statusCode >= 300)) {
|
||||
return reject(new Error(`remote source rejected with status code ${res.statusCode}`))
|
||||
}
|
||||
|
||||
consumeStream(res).then(resolve, reject)
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
.on('error', reject)
|
||||
}
|
||||
|
||||
// use stream/consumers in the future?
|
||||
function consumeStream(res) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = []
|
||||
|
||||
res.on('data', (chunk) => chunks.push(chunk))
|
||||
res.on('end', () => resolve(Buffer.concat(chunks)))
|
||||
res.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
async function createImage(src, alt) {
|
||||
// Empty Buffer / Uint8Array: Image follows the HTML spec (silent completion,
|
||||
// no events) so the promise below would hang. Reject upfront.
|
||||
// See https://github.com/Brooooooklyn/canvas/issues/1255
|
||||
if ((Buffer.isBuffer(src) || src instanceof Uint8Array) && src.length === 0) {
|
||||
throw new Error('loadImage: empty image data')
|
||||
}
|
||||
|
||||
const image = new Image()
|
||||
if (typeof alt === 'string') image.alt = alt
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
image.onload = () => {
|
||||
// Wait for bitmap decode before resolving. SVG sources fire onload
|
||||
// synchronously inside the src setter, where napi >= 3.12 rejects
|
||||
// reentrant &mut borrows of the Image, so decode on a microtask.
|
||||
Promise.resolve()
|
||||
.then(() => image.decode())
|
||||
.then(() => resolve(image), reject)
|
||||
}
|
||||
image.onerror = (event) => reject((event && event[IMAGE_ERROR]) || event)
|
||||
image.src = src
|
||||
})
|
||||
}
|
||||
|
||||
// The URL parser skips leading C0 controls and spaces; the scheme is
|
||||
// ASCII case-insensitive.
|
||||
function isDataUrl(src) {
|
||||
let i = 0
|
||||
while (i < src.length && src.charCodeAt(i) <= 0x20) i++
|
||||
return src.slice(i, i + 5).toLowerCase() === 'data:'
|
||||
}
|
||||
|
||||
function isBufferLike(src) {
|
||||
return (src && src.type === 'Buffer') || Array.isArray(src)
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await fs.promises.access(path, fs.constants.F_OK)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* node-canvas compatibility layer for @napi-rs/canvas.
|
||||
*
|
||||
* Provides a drop-in replacement API matching the `canvas` (node-canvas) npm package.
|
||||
* Quality values for JPEG/WebP use the node-canvas 0-1 scale and are automatically
|
||||
* converted to @napi-rs/canvas's 0-100 scale internally.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Drop-in replacement: change this import
|
||||
* // import { createCanvas, registerFont, loadImage } from 'canvas'
|
||||
* // to this:
|
||||
* import { createCanvas, registerFont, loadImage } from '@napi-rs/canvas/node-canvas'
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
// Re-export types from @napi-rs/canvas that are API-compatible
|
||||
import {
|
||||
Image as NapiImage,
|
||||
ImageData as NapiImageData,
|
||||
Path2D as NapiPath2D,
|
||||
DOMPoint as NapiDOMPoint,
|
||||
DOMMatrix as NapiDOMMatrix,
|
||||
DOMRect as NapiDOMRect,
|
||||
SKRSContext2D,
|
||||
Canvas as NapiCanvas,
|
||||
SvgCanvas,
|
||||
SvgExportFlag,
|
||||
IGlobalFonts,
|
||||
PDFDocument,
|
||||
} from './index'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config interfaces (node-canvas conventions)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PngConfig {
|
||||
/** ZLIB compression level (0-9). Default 6. Out-of-range, fractional and non-number values use the default. */
|
||||
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
||||
/**
|
||||
* libpng row filter bitmask: a non-zero OR of `0x08` (none), `0x10` (sub), `0x20` (up),
|
||||
* `0x40` (average), `0x80` (Paeth). Any other value (including `0`) uses the default (`0xF8`, all filters).
|
||||
*/
|
||||
filters?: number
|
||||
/** Palette for indexed PNGs. Not supported by Skia backend. */
|
||||
palette?: Uint8ClampedArray
|
||||
/** Background color index for indexed PNGs. Not supported by Skia backend. */
|
||||
backgroundIndex?: number
|
||||
/**
|
||||
* Pixels per inch, written as a PNG `pHYs` chunk with the bytes node-canvas
|
||||
* writes, up to 54546055 ppi; a larger value writes 2147483647 px/m, the
|
||||
* PNG maximum. The fraction is dropped. 0, a value below 1, NaN, the
|
||||
* infinities and a non-number write none.
|
||||
*/
|
||||
resolution?: number
|
||||
}
|
||||
|
||||
export interface JpegConfig {
|
||||
/** Quality between 0 and 1. Defaults to 0.75. Converted to 0-100 for Skia. */
|
||||
quality?: number
|
||||
/** Progressive encoding. Accepted for compatibility; not supported by Skia backend. */
|
||||
progressive?: boolean
|
||||
/** 2x2 chroma subsampling. Accepted for compatibility; not supported by Skia backend. */
|
||||
chromaSubsampling?: boolean
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canvas class (with node-canvas compatible methods)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface Canvas extends Omit<NapiCanvas, 'toBuffer' | 'toDataURL'> {
|
||||
/**
|
||||
* Encode the canvas as a PNG and return a Node.js Readable stream.
|
||||
* @param config PNG encoding options (accepted for compatibility)
|
||||
*/
|
||||
createPNGStream(config?: PngConfig): PNGStream
|
||||
|
||||
/**
|
||||
* Encode the canvas as a JPEG and return a Node.js Readable stream.
|
||||
* @param config JPEG encoding options. Quality is 0-1 (default 0.75).
|
||||
*/
|
||||
createJPEGStream(config?: JpegConfig): JPEGStream
|
||||
|
||||
// --- toBuffer overloads (node-canvas conventions) ---
|
||||
|
||||
/** Encode as PNG (default). */
|
||||
toBuffer(): Buffer
|
||||
toBuffer(mimeType: 'image/png', config?: PngConfig): Buffer
|
||||
/** Encode as JPEG. Quality in config is 0-1 (default 0.75). */
|
||||
toBuffer(mimeType: 'image/jpeg', config?: JpegConfig): Buffer
|
||||
/** Get raw unencoded pixel data. */
|
||||
toBuffer(mimeType: 'raw'): Buffer
|
||||
|
||||
/** Async: encode as PNG (default) via callback. */
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void): void
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/png', config?: PngConfig): void
|
||||
/** Async: encode as JPEG via callback. Quality in config is 0-1 (default 0.75). */
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/jpeg', config?: JpegConfig): void
|
||||
|
||||
// --- toDataURL overloads (node-canvas conventions) ---
|
||||
|
||||
/** Encode as PNG data URL (default). */
|
||||
toDataURL(): string
|
||||
toDataURL(mimeType: 'image/png'): string
|
||||
/** Encode as JPEG data URL. Quality is 0-1. */
|
||||
toDataURL(mimeType: 'image/jpeg', quality?: number): string
|
||||
/** Async: encode as data URL via callback. */
|
||||
toDataURL(cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/png', cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/jpeg', cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/jpeg', quality: number, cb: (err: Error | null, result: string) => void): void
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream classes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Readable stream that emits PNG-encoded data. */
|
||||
export class PNGStream extends Readable {}
|
||||
|
||||
/** Readable stream that emits JPEG-encoded data. */
|
||||
export class JPEGStream extends Readable {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Factory functions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new canvas with node-canvas compatible API.
|
||||
* Canvas instances created through this function have `createPNGStream()`,
|
||||
* `createJPEGStream()`, and node-canvas compatible `toBuffer()` overloads.
|
||||
*
|
||||
* When `type` is `'svg'`, returns a `SvgCanvas` which produces vector output
|
||||
* via `getContent()` instead of raster encoding methods.
|
||||
*
|
||||
* @param width Canvas width in pixels
|
||||
* @param height Canvas height in pixels
|
||||
* @param type Canvas type: 'image' (default) or 'svg'
|
||||
*/
|
||||
export function createCanvas(width: number, height: number, type: 'svg'): SvgCanvas
|
||||
export function createCanvas(width: number, height: number, type?: 'image'): Canvas
|
||||
|
||||
/**
|
||||
* Create an ImageData instance.
|
||||
* @param data Pixel data array
|
||||
* @param width Width in pixels
|
||||
* @param height Height in pixels (calculated from data length if omitted)
|
||||
*/
|
||||
export function createImageData(data: Uint8ClampedArray, width: number, height?: number): NapiImageData
|
||||
export function createImageData(width: number, height: number): NapiImageData
|
||||
|
||||
/**
|
||||
* Load an image from a file path, URL, Buffer, or other source.
|
||||
* Returns a Promise that resolves to an Image instance.
|
||||
*/
|
||||
export function loadImage(
|
||||
source: string | URL | Buffer | ArrayBufferLike | Uint8Array | NapiImage | import('stream').Readable,
|
||||
options?: { alt?: string; maxRedirects?: number; requestOptions?: import('http').RequestOptions },
|
||||
): Promise<NapiImage>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Font registration (node-canvas convention)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Register a font file for use in canvas text rendering.
|
||||
* Compatible with node-canvas's `registerFont()`.
|
||||
*
|
||||
* Note: @napi-rs/canvas auto-detects weight and style from font file metadata
|
||||
* (matching browser behavior). The `weight` and `style` properties in fontFace
|
||||
* are accepted for API compatibility.
|
||||
*
|
||||
* @param path Absolute path to the font file (.ttf, .otf, etc.)
|
||||
* @param fontFace Font face properties matching CSS @font-face descriptors
|
||||
*/
|
||||
export function registerFont(path: string, fontFace: { family: string; weight?: string; style?: string }): void
|
||||
|
||||
/**
|
||||
* Deregister all previously registered fonts.
|
||||
* Compatible with node-canvas's `deregisterAllFonts()`.
|
||||
*/
|
||||
export function deregisterAllFonts(): void
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Re-exported classes & values
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Canvas is exported both as a type (the compat interface above) and as a
|
||||
// value (constructor that returns compat Canvas instances at runtime).
|
||||
export declare const Canvas: {
|
||||
new (width: number, height: number): Canvas
|
||||
new (width: number, height: number, flag: SvgExportFlag): SvgCanvas
|
||||
prototype: NapiCanvas
|
||||
}
|
||||
|
||||
export { NapiImage as Image }
|
||||
export { NapiImageData as ImageData }
|
||||
export { NapiPath2D as Path2D }
|
||||
export { NapiDOMPoint as DOMPoint }
|
||||
export { NapiDOMMatrix as DOMMatrix }
|
||||
export { NapiDOMRect as DOMRect }
|
||||
|
||||
// SKRSContext2D is an interface in index.d.ts but a class value at runtime.
|
||||
// Declare as const to export the value for instanceof checks and re-export the type.
|
||||
export type CanvasRenderingContext2D = SKRSContext2D
|
||||
export declare const CanvasRenderingContext2D: { prototype: SKRSContext2D }
|
||||
/** Legacy alias for CanvasRenderingContext2D. */
|
||||
export type Context2d = SKRSContext2D
|
||||
export declare const Context2d: { prototype: SKRSContext2D }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// @napi-rs/canvas extras (not part of node-canvas, but useful)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export { IGlobalFonts }
|
||||
export declare const GlobalFonts: IGlobalFonts & {
|
||||
/** Reload system fonts. Available at runtime but not declared in IGlobalFonts. */
|
||||
loadSystemFonts(): number
|
||||
}
|
||||
export { PDFDocument }
|
||||
export { NapiCanvas as CanvasElement }
|
||||
export { SvgCanvas as SVGCanvas }
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
'use strict'
|
||||
|
||||
const { Readable } = require('node:stream')
|
||||
|
||||
const {
|
||||
createCanvas: _createCanvas,
|
||||
Canvas,
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
GlobalFonts,
|
||||
Image,
|
||||
ImageData,
|
||||
Path2D,
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
loadImage,
|
||||
PDFDocument,
|
||||
SvgExportFlag,
|
||||
} = require('./index.js')
|
||||
|
||||
// CanvasRenderingContext2D is not re-exported by index.js, grab from native bindings
|
||||
const { CanvasRenderingContext2D } = require('./js-binding')
|
||||
|
||||
// node-canvas defaults JPEG quality to 0.75 across all paths.
|
||||
// @napi-rs/canvas native default is 0.92 (matching Blink/Chrome).
|
||||
const NODE_CANVAS_DEFAULT_QUALITY = 0.75
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream classes (node-canvas returns Node.js Readable streams)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class PNGStream extends Readable {
|
||||
constructor(canvas, options) {
|
||||
super()
|
||||
this._canvas = canvas
|
||||
this._options = options || {}
|
||||
this._done = false
|
||||
}
|
||||
|
||||
_read() {
|
||||
if (this._done) return
|
||||
this._done = true
|
||||
this._canvas
|
||||
.encode('png', _pngOptions(this._options))
|
||||
.then((buf) => {
|
||||
this.push(buf)
|
||||
this.push(null)
|
||||
})
|
||||
.catch((err) => {
|
||||
this.destroy(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
class JPEGStream extends Readable {
|
||||
constructor(canvas, options) {
|
||||
super()
|
||||
this._canvas = canvas
|
||||
const opts = options || {}
|
||||
// node-canvas quality: 0-1 (default 0.75), encode() expects 0-100
|
||||
this._quality = Math.round((opts.quality != null ? opts.quality : NODE_CANVAS_DEFAULT_QUALITY) * 100)
|
||||
this._done = false
|
||||
}
|
||||
|
||||
_read() {
|
||||
if (this._done) return
|
||||
this._done = true
|
||||
this._canvas
|
||||
.encode('jpeg', this._quality)
|
||||
.then((buf) => {
|
||||
this.push(buf)
|
||||
this.push(null)
|
||||
})
|
||||
.catch((err) => {
|
||||
this.destroy(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quality normalization helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MIME_FORMAT_MAP = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpeg',
|
||||
'image/webp': 'webp',
|
||||
'image/avif': 'avif',
|
||||
'image/gif': 'gif',
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract quality from a node-canvas config object or number.
|
||||
* Returns the raw 0-1 quality value, defaulting to NODE_CANVAS_DEFAULT_QUALITY
|
||||
* for JPEG/WebP when not specified.
|
||||
*
|
||||
* @param {string} mime
|
||||
* @param {number|object|undefined} configOrQuality
|
||||
* @returns {number|undefined} 0-1 scale for JPEG/WebP, undefined for other mimes
|
||||
*/
|
||||
function _extractQuality(mime, configOrQuality) {
|
||||
if (mime !== 'image/jpeg' && mime !== 'image/webp') return undefined
|
||||
if (configOrQuality == null) return NODE_CANVAS_DEFAULT_QUALITY
|
||||
if (typeof configOrQuality === 'number') return configOrQuality
|
||||
if (typeof configOrQuality === 'object' && configOrQuality.quality != null) {
|
||||
return configOrQuality.quality
|
||||
}
|
||||
return NODE_CANVAS_DEFAULT_QUALITY
|
||||
}
|
||||
|
||||
/**
|
||||
* The native PNG options for a node-canvas PngConfig: `resolution` (pHYs chunk),
|
||||
* `compressionLevel` (zlib 0-9) and `filters` (libpng filter bitmask); undefined
|
||||
* when none of them is a number, so the native call stays a plain PNG encode.
|
||||
*
|
||||
* @param {object|undefined} config
|
||||
* @returns {{ resolution?: number, compressionLevel?: number, filters?: number }|undefined}
|
||||
*/
|
||||
function _pngOptions(config) {
|
||||
if (config === null || typeof config !== 'object') return undefined
|
||||
const resolution = config.resolution
|
||||
const compressionLevel = config.compressionLevel
|
||||
const filters = config.filters
|
||||
const options = {}
|
||||
let hasOption = false
|
||||
if (typeof resolution === 'number') {
|
||||
options.resolution = resolution
|
||||
hasOption = true
|
||||
}
|
||||
if (typeof compressionLevel === 'number') {
|
||||
options.compressionLevel = compressionLevel
|
||||
hasOption = true
|
||||
}
|
||||
if (typeof filters === 'number') {
|
||||
options.filters = filters
|
||||
hasOption = true
|
||||
}
|
||||
return hasOption ? options : undefined
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Compat methods added to each canvas instance created via this module
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Keep references to the original prototype methods
|
||||
const _origToBuffer = CanvasElement.prototype.toBuffer
|
||||
const _origToDataURL = CanvasElement.prototype.toDataURL
|
||||
|
||||
function _compatCreatePNGStream(options) {
|
||||
return new PNGStream(this, options)
|
||||
}
|
||||
|
||||
function _compatCreateJPEGStream(options) {
|
||||
return new JPEGStream(this, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* node-canvas compatible toBuffer:
|
||||
* - toBuffer() → PNG (sync)
|
||||
* - toBuffer('image/png', config?) → PNG (sync)
|
||||
* - toBuffer('image/jpeg', config?) → JPEG (sync, quality 0-1)
|
||||
* - toBuffer('raw') → raw pixel data (sync)
|
||||
* - toBuffer(callback) → PNG (async)
|
||||
* - toBuffer(callback, mime, config?) → specified format (async)
|
||||
*/
|
||||
function _compatToBuffer(mimeOrCallback, configOrQuality) {
|
||||
// Callback form: toBuffer(callback) or toBuffer(callback, mime, config)
|
||||
if (typeof mimeOrCallback === 'function') {
|
||||
const callback = mimeOrCallback
|
||||
const mime = typeof configOrQuality === 'string' ? configOrQuality : 'image/png'
|
||||
const config = arguments[2]
|
||||
|
||||
if (mime === 'raw') {
|
||||
let buf
|
||||
try {
|
||||
buf = this.data()
|
||||
} catch (err) {
|
||||
callback(err)
|
||||
return
|
||||
}
|
||||
callback(null, buf)
|
||||
return
|
||||
}
|
||||
|
||||
const format = MIME_FORMAT_MAP[mime]
|
||||
if (!format) {
|
||||
callback(new TypeError(`Unsupported MIME type "${mime}". Supported: ${Object.keys(MIME_FORMAT_MAP).join(', ')}`))
|
||||
return
|
||||
}
|
||||
const q = _extractQuality(mime, config)
|
||||
const options = format === 'png' ? _pngOptions(config) : q != null ? Math.round(q * 100) : undefined
|
||||
this.encode(format, options).then(
|
||||
(buf) => callback(null, buf),
|
||||
(err) => callback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Sync: no args → PNG
|
||||
if (mimeOrCallback === undefined) {
|
||||
return _origToBuffer.call(this, 'image/png')
|
||||
}
|
||||
|
||||
// Sync: raw pixel data
|
||||
if (mimeOrCallback === 'raw') {
|
||||
return this.data()
|
||||
}
|
||||
|
||||
// Sync: PNG takes the resolution; JPEG / WebP a quality (0-1) scaled to
|
||||
// 0-100 for native toBuffer
|
||||
if (mimeOrCallback === 'image/png') {
|
||||
return _origToBuffer.call(this, mimeOrCallback, _pngOptions(configOrQuality))
|
||||
}
|
||||
const q = _extractQuality(mimeOrCallback, configOrQuality)
|
||||
return _origToBuffer.call(this, mimeOrCallback, q != null ? Math.round(q * 100) : undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* node-canvas compatible toDataURL:
|
||||
* - toDataURL() → PNG data URL (sync)
|
||||
* - toDataURL('image/jpeg', quality) → JPEG data URL, quality 0-1 (sync)
|
||||
* - toDataURL(callback) → PNG data URL (async)
|
||||
* - toDataURL(mime, callback) → data URL (async)
|
||||
* - toDataURL(mime, quality, callback) → data URL with quality (async)
|
||||
*/
|
||||
function _compatToDataURL(mimeOrCallback, qualityOrCallback) {
|
||||
// toDataURL(callback)
|
||||
if (typeof mimeOrCallback === 'function') {
|
||||
this.toDataURLAsync('image/png').then(
|
||||
(url) => mimeOrCallback(null, url),
|
||||
(err) => mimeOrCallback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
// toDataURL(mime, callback)
|
||||
if (typeof qualityOrCallback === 'function') {
|
||||
this.toDataURLAsync(mimeOrCallback, _extractQuality(mimeOrCallback, undefined)).then(
|
||||
(url) => qualityOrCallback(null, url),
|
||||
(err) => qualityOrCallback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
// toDataURL(mime, quality, callback)
|
||||
const cb = arguments[2]
|
||||
if (typeof cb === 'function') {
|
||||
// Native toDataURLAsync expects 0-1 (f64) — pass quality through as-is
|
||||
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
|
||||
this.toDataURLAsync(mimeOrCallback, quality).then(
|
||||
(url) => cb(null, url),
|
||||
(err) => cb(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Sync form: native toDataURL expects 0-1 (f64) — pass quality through as-is
|
||||
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
|
||||
return _origToDataURL.call(this, mimeOrCallback, quality)
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach node-canvas compatible methods to a CanvasElement instance.
|
||||
*/
|
||||
function _addCompatMethods(canvas) {
|
||||
canvas.createPNGStream = _compatCreatePNGStream
|
||||
canvas.createJPEGStream = _compatCreateJPEGStream
|
||||
canvas.toBuffer = _compatToBuffer
|
||||
canvas.toDataURL = _compatToDataURL
|
||||
return canvas
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API: registerFont / deregisterAllFonts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Track FontKeys from registerFont() so deregisterAllFonts() can remove
|
||||
// only user-registered fonts (matching node-canvas behavior which leaves
|
||||
// system fonts untouched).
|
||||
const _registeredFontKeys = []
|
||||
|
||||
/**
|
||||
* Register a font file with the specified font face properties.
|
||||
* Compatible with node-canvas's registerFont(path, { family, weight?, style? }).
|
||||
*
|
||||
* Note: @napi-rs/canvas auto-detects weight and style from font file metadata
|
||||
* (matching browser behavior). The weight and style properties in fontFace are
|
||||
* accepted for API compatibility but the actual values are read from the font.
|
||||
*
|
||||
* @param {string} path Absolute path to the font file (.ttf, .otf, etc.)
|
||||
* @param {{ family: string, weight?: string, style?: string }} fontFace
|
||||
*/
|
||||
function registerFont(path, fontFace) {
|
||||
if (!fontFace || typeof fontFace.family !== 'string') {
|
||||
throw new TypeError('registerFont requires a fontFace with a "family" property')
|
||||
}
|
||||
const key = GlobalFonts.registerFromPath(path, fontFace.family)
|
||||
if (!key) {
|
||||
throw new Error(`Failed to register font from "${path}" with family "${fontFace.family}"`)
|
||||
}
|
||||
_registeredFontKeys.push(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deregister all fonts previously registered via registerFont().
|
||||
* Compatible with node-canvas's deregisterAllFonts() which only removes
|
||||
* user-registered fonts and leaves system fonts untouched.
|
||||
*/
|
||||
function deregisterAllFonts() {
|
||||
if (_registeredFontKeys.length > 0) {
|
||||
GlobalFonts.removeBatch(_registeredFontKeys)
|
||||
_registeredFontKeys.length = 0
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API: createCanvas / createImageData
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new canvas instance with node-canvas compatible API.
|
||||
*
|
||||
* @param {number} width
|
||||
* @param {number} height
|
||||
* @param {'image'|'svg'} [type='image']
|
||||
* @returns {Canvas}
|
||||
*/
|
||||
function createCanvas(width, height, type) {
|
||||
if (type === 'svg') {
|
||||
// SvgExportFlag enum requires a valid variant; NoPrettyXML (0x02) is the
|
||||
// least impactful on rendering behavior (only affects XML whitespace).
|
||||
return _createCanvas(width, height, SvgExportFlag.NoPrettyXML)
|
||||
}
|
||||
if (type === 'pdf') {
|
||||
throw new Error(
|
||||
'createCanvas with type "pdf" is not supported. Use the PDFDocument class from @napi-rs/canvas directly.',
|
||||
)
|
||||
}
|
||||
if (type != null && type !== 'image') {
|
||||
throw new TypeError(`createCanvas: unknown type "${type}". Supported types: "image", "svg".`)
|
||||
}
|
||||
return _addCompatMethods(_createCanvas(width, height))
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ImageData instance.
|
||||
* Compatible with node-canvas's createImageData().
|
||||
*
|
||||
* @param {Uint8ClampedArray|number} dataOrWidth
|
||||
* @param {number} widthOrHeight
|
||||
* @param {number} [height]
|
||||
* @returns {ImageData}
|
||||
*/
|
||||
function createImageData(dataOrWidth, widthOrHeight, height) {
|
||||
if (typeof dataOrWidth === 'number') {
|
||||
return new ImageData(dataOrWidth, widthOrHeight)
|
||||
}
|
||||
if (height != null) {
|
||||
return new ImageData(dataOrWidth, widthOrHeight, height)
|
||||
}
|
||||
return new ImageData(dataOrWidth, widthOrHeight)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canvas constructor wrapper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// In node-canvas, `new Canvas(w, h)` and `createCanvas(w, h)` produce
|
||||
// equivalent canvases. Wrap the native Canvas constructor so that
|
||||
// `new Canvas(w, h)` also gets compat methods, without polluting the
|
||||
// prototype (which would affect @napi-rs/canvas users who don't use
|
||||
// this compat layer).
|
||||
const CompatCanvas = new Proxy(Canvas, {
|
||||
construct(target, args) {
|
||||
const canvas = new target(...args)
|
||||
if (canvas instanceof CanvasElement) {
|
||||
return _addCompatMethods(canvas)
|
||||
}
|
||||
return canvas
|
||||
},
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exports (matches node-canvas export shape)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
// Factory functions
|
||||
Canvas: CompatCanvas,
|
||||
createCanvas,
|
||||
createImageData,
|
||||
loadImage,
|
||||
registerFont,
|
||||
deregisterAllFonts,
|
||||
|
||||
// Classes
|
||||
Image,
|
||||
ImageData,
|
||||
CanvasRenderingContext2D,
|
||||
Context2d: CanvasRenderingContext2D,
|
||||
PNGStream,
|
||||
JPEGStream,
|
||||
Path2D,
|
||||
|
||||
// Geometry
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
|
||||
// @napi-rs/canvas extras (available but not part of node-canvas)
|
||||
GlobalFonts,
|
||||
PDFDocument,
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
{
|
||||
"name": "@napi-rs/canvas",
|
||||
"version": "1.2.0",
|
||||
"description": "Canvas for Node.js with skia backend",
|
||||
"main": "index.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Brooooooklyn/canvas.git"
|
||||
},
|
||||
"workspaces": [
|
||||
"e2e/*"
|
||||
],
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"napi-rs",
|
||||
"NAPI",
|
||||
"N-API",
|
||||
"Rust",
|
||||
"node-addon",
|
||||
"node-addon-api",
|
||||
"canvas",
|
||||
"image",
|
||||
"pdf",
|
||||
"svg",
|
||||
"skia"
|
||||
],
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"index.js",
|
||||
"geometry.js",
|
||||
"js-binding.js",
|
||||
"load-image.js",
|
||||
"node-canvas.js",
|
||||
"node-canvas.d.ts"
|
||||
],
|
||||
"napi": {
|
||||
"binaryName": "skia",
|
||||
"targets": [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"aarch64-pc-windows-msvc",
|
||||
"armv7-unknown-linux-gnueabihf",
|
||||
"x86_64-unknown-linux-musl",
|
||||
"aarch64-unknown-linux-gnu",
|
||||
"aarch64-unknown-linux-musl",
|
||||
"aarch64-apple-darwin",
|
||||
"aarch64-linux-android",
|
||||
"riscv64-unknown-linux-gnu"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"artifacts": "napi artifacts",
|
||||
"build": "napi build --platform --release --js js-binding.js",
|
||||
"build:debug": "napi build --platform --js js-binding.js",
|
||||
"example-lottie": "yarn oxnode ./example/lottie-to-video.ts",
|
||||
"format": "run-p format:source format:rs format:toml",
|
||||
"format:rs": "cargo fmt",
|
||||
"format:source": "prettier . -w",
|
||||
"format:toml": "taplo format",
|
||||
"lint": "oxlint",
|
||||
"prepublishOnly": "pinst --disable && napi prepublish -t npm",
|
||||
"postpublish": "pinst --enable",
|
||||
"test:ci": "NODE_OPTIONS='--import=core-js/proposals/iterator-helpers.js' ava -c 1",
|
||||
"test": "NODE_OPTIONS='--import=core-js/proposals/iterator-helpers.js' ava",
|
||||
"e2e": "yarn workspace @napi-rs/canvas-e2e-webpack test",
|
||||
"e2e:electron": "yarn workspace @napi-rs/canvas-e2e-electron test",
|
||||
"version": "napi version && conventional-changelog -p angular -i CHANGELOG.md -s && git add ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jimp/core": "^1.6.0",
|
||||
"@jimp/custom": "^0.22.12",
|
||||
"@jimp/jpeg": "^0.22.12",
|
||||
"@jimp/png": "^0.22.12",
|
||||
"@napi-rs/cli": "^3.8.3",
|
||||
"@napi-rs/webcodecs": "^1.1.1",
|
||||
"@node-rs/crc32": "^1.10.6",
|
||||
"@octokit/rest": "^22.0.1",
|
||||
"@oxc-node/cli": "^1.0.0",
|
||||
"@oxc-node/core": "^1.0.0",
|
||||
"@taplo/cli": "^0.7.0",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"@types/node": "^26.0.0",
|
||||
"@types/semver": "^7",
|
||||
"ava": "^8.0.0",
|
||||
"canvas": "^3.2.0",
|
||||
"canvaskit-wasm": "^0.42.0",
|
||||
"colorette": "^2.0.20",
|
||||
"conventional-changelog-cli": "^5.0.0",
|
||||
"core-js": "^3.47.0",
|
||||
"echarts": "^6.0.0",
|
||||
"electron": "^45.0.0",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^17.0.0",
|
||||
"lodash": "^4.17.21",
|
||||
"npm-run-all2": "^9.0.0",
|
||||
"oxlint": "^1.34.0",
|
||||
"oxlint-tsgolint": "^7.0.0",
|
||||
"pdfjs-dist": "6.5.438",
|
||||
"pinst": "^3.0.0",
|
||||
"png.js": "^0.2.1",
|
||||
"prettier": "^3.7.4",
|
||||
"pretty-bytes": "^7.1.0",
|
||||
"semver": "^7.7.3",
|
||||
"smol-toml": "^1.9.0",
|
||||
"table": "^6.9.0",
|
||||
"typescript": "^7.0.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.@(js|ts|tsx|yml|yaml|md|json|html)": [
|
||||
"prettier --write"
|
||||
],
|
||||
"*.@(js|ts|tsx)": [
|
||||
"oxlint --fix"
|
||||
]
|
||||
},
|
||||
"ava": {
|
||||
"nodeArguments": [
|
||||
"--import=@oxc-node/core/register",
|
||||
"--import=core-js/proposals/promise-with-resolvers.js"
|
||||
],
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"files": [
|
||||
"__test__/**/*.spec.ts",
|
||||
"scripts/__test__/**/*.spec.ts"
|
||||
],
|
||||
"workerThreads": false,
|
||||
"cache": false,
|
||||
"timeout": "3m",
|
||||
"environmentVariables": {
|
||||
"SWC_NODE_PROJECT": "./tsconfig.json",
|
||||
"NODE_ENV": "ava"
|
||||
}
|
||||
},
|
||||
"prettier": {
|
||||
"printWidth": 120,
|
||||
"semi": false,
|
||||
"trailingComma": "all",
|
||||
"singleQuote": true,
|
||||
"arrowParens": "always"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"packageManager": "yarn@4.18.1",
|
||||
"dependenciesMeta": {
|
||||
"canvas": {
|
||||
"built": true
|
||||
}
|
||||
},
|
||||
"resolutions": {
|
||||
"@napi-rs/canvas": "workspace:"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas-linux-x64-gnu": "1.2.0",
|
||||
"@napi-rs/canvas-darwin-x64": "1.2.0",
|
||||
"@napi-rs/canvas-win32-x64-msvc": "1.2.0",
|
||||
"@napi-rs/canvas-win32-arm64-msvc": "1.2.0",
|
||||
"@napi-rs/canvas-linux-arm-gnueabihf": "1.2.0",
|
||||
"@napi-rs/canvas-linux-x64-musl": "1.2.0",
|
||||
"@napi-rs/canvas-linux-arm64-gnu": "1.2.0",
|
||||
"@napi-rs/canvas-linux-arm64-musl": "1.2.0",
|
||||
"@napi-rs/canvas-darwin-arm64": "1.2.0",
|
||||
"@napi-rs/canvas-android-arm64": "1.2.0",
|
||||
"@napi-rs/canvas-linux-riscv64-gnu": "1.2.0"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user