Initial commit
This commit is contained in:
970
node_modules/canvas/CHANGELOG.md
generated
vendored
Normal file
970
node_modules/canvas/CHANGELOG.md
generated
vendored
Normal file
@@ -0,0 +1,970 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this
|
||||
project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
(Unreleased)
|
||||
==================
|
||||
### Changed
|
||||
### Added
|
||||
### Fixed
|
||||
|
||||
2.8.0
|
||||
==================
|
||||
### Changed
|
||||
* Upgrade dtslint
|
||||
* Upgrade node-pre-gyp to 1.0.0. Note that if you are using special node-pre-gyp
|
||||
features like `node_pre_gyp_accessKeyId`, you may need to make changes to your
|
||||
installation procedure. See https://github.com/mapbox/node-pre-gyp/blob/master/CHANGELOG.md#100.
|
||||
* Add Node.js v16 to CI.
|
||||
* The C++ class method `nBytes()` now returns a size_t. (Because this is a C++
|
||||
method only, this is not considered a breaking change.)
|
||||
* Export type NodeCanvasRenderingContext2D so you can pass the current context
|
||||
to functions (TypeScript).
|
||||
### Added
|
||||
* Add support for `inverse()` and `invertSelf()` to `DOMMatrix` (#1648)
|
||||
* Add support for `context.getTransform()` ([#1769](https://github.com/Automattic/node-canvas/pull/1769))
|
||||
* Add support for `context.setTransform(dommatrix)` ([#1769](https://github.com/Automattic/node-canvas/pull/1769))
|
||||
### Fixed
|
||||
* Fix `actualBoundingBoxLeft` and `actualBoundingBoxRight` returned by `measureText` to be the ink rect ([#1776](https://github.com/Automattic/node-canvas/pull/1776), fixes [#1703](https://github.com/Automattic/node-canvas/issues/1703)).
|
||||
* Fix Pango logging "expect ugly output" on Windows (#1643)
|
||||
* Fix benchmark for createPNGStream (#1672)
|
||||
* Fix dangling reference in BackendOperationNotAvailable exception (#1740)
|
||||
* Fix always-false comparison warning in Canvas.cc.
|
||||
* Fix Node.js crash when throwing from an onload or onerror handler.
|
||||
|
||||
2.7.0
|
||||
==================
|
||||
### Changed
|
||||
* Switch CI to Github Actions. (Adds Windows and macOS builds.)
|
||||
* Switch prebuilds to GitHub actions in the Automattic/node-canvas repository.
|
||||
Previously these were in the [node-gfx/node-canvas-prebuilt](https://github.com/node-gfx/node-canvas-prebuilt)
|
||||
and triggered manually.
|
||||
* Speed up `fillStyle=` and `strokeStyle=`
|
||||
### Added
|
||||
* Export `rsvgVersion`.
|
||||
### Fixed
|
||||
* Fix BMP issues. (#1497)
|
||||
* Update typings to support jpg and addPage on NodeCanvasRenderingContext2D (#1509)
|
||||
* Fix assertion failure when using Visual Studio Code debugger to inspect Image prototype (#1534)
|
||||
* Fix signed/unsigned comparison warning introduced in 2.6.0, and function cast warnings with GCC8+
|
||||
* Fix to compile without JPEG support (#1593).
|
||||
* Fix compile errors with cairo
|
||||
* Fix Image#complete if the image failed to load.
|
||||
* Upgrade node-pre-gyp to v0.15.0 to use latest version of needle to fix error when downloading prebuilds.
|
||||
* Don't throw if `fillStyle` or `strokeStyle` is set to an object, but that object is not a Gradient or Pattern. (This behavior was non-standard: invalid inputs are supposed to be ignored.)
|
||||
|
||||
2.6.1
|
||||
==================
|
||||
### Fixed
|
||||
* Ignore `maxWidth` in `fillText` and `strokeText` if it is undefined
|
||||
* Fix crash (assertion failure) in Node.js 12.x when patterns or gradients are used
|
||||
* Fix crash (check failure) in Node.js 12.x when using RGB16_565 format. (The
|
||||
underlying arraybuffer was incorrectly sized.)
|
||||
* Fix rendering error when applying shadow width line style (lineCap lineJoin lineDash)
|
||||
|
||||
2.6.0
|
||||
==================
|
||||
### Changed
|
||||
* Allow larger buffers to be returned from `toBuffer('raw')`.
|
||||
### Added
|
||||
* Support for various BMP headers and color depths (#1435)
|
||||
### Fixed
|
||||
* Fix crash when changing canvas width/height while `fillStyle` or `strokeStyle`
|
||||
was set to a `CanvasPattern` or `CanvasGradient` (#1357).
|
||||
* Fix crash when changing width/height of SVG canvases (#1380).
|
||||
* Fix crash when using `toBuffer('raw')` with large canvases (#1158).
|
||||
* Clarified meaning of byte ordering for `toBuffer('raw')` in readme. (#1416)
|
||||
* Fix package.json Typings field to point to Declaration file (#1432)
|
||||
* Properly check return value from `Set` and `Call`. (#1415)
|
||||
* Use `Get` version from `Nan` instead of `v8`. (#1415)
|
||||
|
||||
2.5.0
|
||||
==================
|
||||
### Added
|
||||
* Support redirects when fetching images (using [simple-get](https://github.com/feross/simple-get)) (#1398)
|
||||
* Support Node.js v12
|
||||
### Fixed
|
||||
* Fix object literal & arrow function syntax usage for IE.
|
||||
|
||||
2.4.1
|
||||
==================
|
||||
### Fixed
|
||||
* Guard JPEG width/height against maximum supported (#1385)
|
||||
* Fix electron 5 and node 12 compatibility
|
||||
* Fix encoding options (quality) parameter in `canvas.toDataURL()`
|
||||
|
||||
2.4.0
|
||||
==================
|
||||
### Added
|
||||
* (Actually) added `resolution` option for `canvas.toBuffer("image/png")` and
|
||||
`canvas.createPNGStream()`. This was documented since 2.0.0 but not working.
|
||||
* Add typescript definitions.
|
||||
### Fixed
|
||||
* PDF metadata (added in 2.3.0) wasn't being set with `canvas.createPDFStream()`
|
||||
* Fix custom "inspect" function deprecation warnings (#1326)
|
||||
|
||||
2.3.1
|
||||
==================
|
||||
### Fixed
|
||||
* Fix `canvas.toBuffer()` for JPEGs (#1350)
|
||||
|
||||
2.3.0
|
||||
==================
|
||||
### Added
|
||||
* Add support for multiple PDF page sizes
|
||||
* Add support for embedding document metadata in PDFs
|
||||
|
||||
### Fixed
|
||||
* Don't crash when font string is invalid (bug since 2.2.0) (#1328)
|
||||
* Fix memory leak in `canvas.toBuffer()` (#1202, #1296)
|
||||
* Fix memory leak in `ctx.font=` (#1202)
|
||||
|
||||
2.2.0
|
||||
==================
|
||||
### Added
|
||||
* BMP support
|
||||
|
||||
### Fixed
|
||||
* Reset context on resurface (#1292)
|
||||
* Support Jest test framework (#1311)
|
||||
|
||||
2.1.0
|
||||
==================
|
||||
### Added
|
||||
* Warn when building with old, unsupported versions of cairo or libjpeg.
|
||||
|
||||
2.0.0
|
||||
==================
|
||||
|
||||
**Upgrading from 1.x**
|
||||
```js
|
||||
// (1) The Canvas constructor is no longer the default export from the module.
|
||||
/* old: */
|
||||
const Canvas = require('canvas')
|
||||
const mycanvas = new Canvas(width, height)
|
||||
/* new: */
|
||||
const { createCanvas, Canvas } = require('canvas')
|
||||
const mycanvas = createCanvas(width, height)
|
||||
mycanvas instanceof Canvas // true
|
||||
|
||||
/* old: */
|
||||
const Canvas = require('canvas')
|
||||
const myimg = new Canvas.Image()
|
||||
/* new: */
|
||||
const { Image } = require('canvas')
|
||||
const myimg = new Image()
|
||||
|
||||
// (2) The quality argument for canvas.createJPEGStream/canvas.jpegStream now
|
||||
// goes from 0 to 1 instead of from 0 to 100:
|
||||
canvas.createJPEGStream({ quality: 50 }) // old
|
||||
canvas.createJPEGStream({ quality: 0.5 }) // new
|
||||
|
||||
// (3) The ZLIB compression level and PNG filter options for canvas.toBuffer are
|
||||
// now named instead of positional arguments:
|
||||
canvas.toBuffer(undefined, 3, canvas.PNG_FILTER_NONE) // old
|
||||
canvas.toBuffer(undefined, { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE }) // new
|
||||
// or specify the mime type explicitly:
|
||||
canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE }) // new
|
||||
|
||||
// (4) #2 also applies for canvas.pngStream, although these arguments were not
|
||||
// documented:
|
||||
canvas.pngStream(3, canvas.PNG_FILTER_NONE) // old
|
||||
canvas.pngStream({ compressionLevel: 3, filters: canvas.PNG_FILTER_NONE }) // new
|
||||
|
||||
// (5) canvas.syncPNGStream() and canvas.syncJPEGStream() have been removed:
|
||||
canvas.syncPNGStream() // old
|
||||
canvas.createSyncPNGStream() // old
|
||||
canvas.createPNGStream() // new
|
||||
|
||||
canvas.syncJPEGStream() // old
|
||||
canvas.createSyncJPEGStream() // old
|
||||
canvas.createJPEGStream() // new
|
||||
|
||||
// (6) Context2d.filter has been renamed to context2d.quality to avoid a
|
||||
// conflict with the new standard 'filter' property.
|
||||
context.filter = 'best' // old
|
||||
context.quality = 'best' // new
|
||||
```
|
||||
|
||||
### Breaking
|
||||
* Drop support for Node.js <6.x
|
||||
* Remove sync stream functions (bc53059). Note that most streams are still
|
||||
synchronous (run in the main thread); this change just removed `syncPNGStream`
|
||||
and `syncJPEGStream`.
|
||||
* Pango is now *required* on all platforms (7716ae4).
|
||||
* Make the `quality` argument for JPEG output go from 0 to 1 to match HTML spec.
|
||||
* Make the `compressionLevel` and `filters` arguments for `canvas.toBuffer()`
|
||||
named instead of positional. Same for `canvas.pngStream()`, although these
|
||||
arguments were not documented.
|
||||
* See also: *Correct some of the `globalCompositeOperator` types* under
|
||||
**Fixed**. These changes were bug-fixes, but will break existing code relying
|
||||
on the incorrect types.
|
||||
* Rename `context2d.filter` to `context2d.quality` to avoid a conflict with the
|
||||
new standard 'filter' property. Note that the standard 'filter' property is
|
||||
not yet implemented.
|
||||
|
||||
### Fixed
|
||||
* Fix build with SVG support enabled (#1123)
|
||||
* Prevent segfaults caused by loading invalid fonts (#1105)
|
||||
* Fix memory leak in font loading
|
||||
* Port has_lib.sh to javascript (#872)
|
||||
* Correctly sample the edge of images when scaling (#1084)
|
||||
* Detect CentOS libjpeg path (b180ea5)
|
||||
* Improve measureText accuracy (2bbfec5)
|
||||
* Fix memory leak when image callbacks reference the image (1f4b646)
|
||||
* Fix putImageData(data, negative, negative) (2102e25)
|
||||
* Fix SVG recognition when loading from buffer (77749e6)
|
||||
* Re-rasterize SVG when drawing to a context and dimensions changed (79bf232)
|
||||
* Prevent JPEG errors from crashing process (#1124)
|
||||
* Improve handling of invalid arguments (#1129)
|
||||
* Fix repeating patterns when drawing a canvas to itself (#1136)
|
||||
* Prevent segfaults caused by creating a too large canvas
|
||||
* Fix parse-font regex to allow for whitespaces.
|
||||
* Allow assigning non-string values to fillStyle and strokeStyle
|
||||
* Fix drawing zero-width and zero-height images.
|
||||
* Fix DEP0005 deprecation warning
|
||||
* Don't assume `data:` URIs assigned to `img.src` are always base64-encoded
|
||||
* Fix formatting of color strings (e.g. `ctx.fillStyle`) on 32-bit platforms
|
||||
* Explicitly export symbols for the C++ API
|
||||
* Named CSS colors should match case-insensitive
|
||||
* Correct some of the `globalCompositeOperator` types to match the spec:
|
||||
* "hsl-hue" is now "hue"
|
||||
* "hsl-saturation" is now "saturation"
|
||||
* "hsl-color" is now "color"
|
||||
* "hsl-luminosity" is now "luminosity"
|
||||
* "darker" is now "darken"
|
||||
* "dest" is now "destination"
|
||||
* "add" is removed (but is the same as "lighter")
|
||||
* "source" is now "copy"
|
||||
* Provide better, Node.js core-style coded errors for failed sys calls. (For
|
||||
example, provide an error with code 'ENOENT' if setting `img.src` to a path
|
||||
that does not exist.)
|
||||
* Support reading CMYK, YCCK JPEGs.
|
||||
* Hide `Image.prototype.source`
|
||||
* Fix behavior of maxWidth (#1088)
|
||||
* Fix behavior of textAlignment with maxWidth (#1253)
|
||||
|
||||
### Added
|
||||
* Prebuilds (#992) with different libc versions to the prebuilt binary (#1140)
|
||||
* Support `canvas.getContext("2d", {alpha: boolean})` and
|
||||
`canvas.getContext("2d", {pixelFormat: "..."})`
|
||||
* Support indexed PNG encoding.
|
||||
* Support `currentTransform` (d6714ee)
|
||||
* Export `CanvasGradient` (6a4c0ab)
|
||||
* Support #RGBA , #RRGGBBAA hex colors (10a82ec)
|
||||
* Support maxWidth arg for fill/strokeText (175b40d)
|
||||
* Support image.naturalWidth/Height (a5915f8)
|
||||
* Render SVG img elements when librsvg is available (1baf00e)
|
||||
* Support ellipse method (4d4a726)
|
||||
* Browser-compatible API (6a29a23)
|
||||
* Support for jpeg on Windows (42e9a74)
|
||||
* Support for backends (1a6dffe)
|
||||
* Support for `canvas.toBuffer("image/jpeg")`
|
||||
* Unified configuration options for `canvas.toBuffer()`, `canvas.pngStream()`
|
||||
and `canvas.jpegStream()`
|
||||
* ~~Added `resolution` option for `canvas.toBuffer("image/png")` and
|
||||
`canvas.createPNGStream()`~~ this was not working
|
||||
* Support for `canvas.toDataURI("image/jpeg")` (sync)
|
||||
* Support for `img.src = <url>` to match browsers
|
||||
* Support reading data URL on `img.src`
|
||||
* Readme: add dependencies command for OpenBSD
|
||||
* Throw error if calling jpegStream when canvas was not built with JPEG support
|
||||
* Emit error if trying to load GIF, SVG or JPEG image when canvas was not built
|
||||
with support for that format
|
||||
|
||||
1.6.x (unreleased)
|
||||
==================
|
||||
### Fixed
|
||||
* Make setLineDash able to handle full zeroed dashes (b8cf1d7)
|
||||
* Fix reading fillStyle after setting it from gradient to color (a84b2bc)
|
||||
|
||||
### Added
|
||||
* Support for pattern repeat and no-repeat (#1066)
|
||||
* Support for context globalAlpha for gradients and patterns (#1064)
|
||||
|
||||
1.6.9 / 2017-12-20
|
||||
==================
|
||||
### Fixed
|
||||
* Fix some instances of crashes (7c9ec58, 8b792c3)
|
||||
* Fix node 0.x compatibility (dca33f7)
|
||||
|
||||
1.6.8 / 2017-12-12
|
||||
==================
|
||||
### Fixed
|
||||
* Faster, more compliant parseFont (4625efa, 37cd969)
|
||||
|
||||
1.6.7 / 2017-09-08
|
||||
==================
|
||||
### Fixed
|
||||
* Minimal backport of #985 (rotated text baselines) (c19edb8)
|
||||
|
||||
1.6.6 / 2017-05-03
|
||||
==================
|
||||
### Fixed
|
||||
* Use .node extension for requiring native module so webpack works (1b05599)
|
||||
* Correct text baseline calculation (#1037)
|
||||
|
||||
1.6.5 / 2017-03-18
|
||||
==================
|
||||
### Changed
|
||||
* Parse font using parse-css-font and units-css (d316416)
|
||||
|
||||
1.6.4 / 2017-02-26
|
||||
==================
|
||||
### Fixed
|
||||
* Make sure Canvas#toDataURL is always async if callback is passed (8586d72)
|
||||
|
||||
1.6.3 / 2017-02-14
|
||||
==================
|
||||
### Fixed
|
||||
* Fix isnan() and isinf() on clang (5941e13)
|
||||
|
||||
1.6.2 / 2016-10-30
|
||||
==================
|
||||
### Fixed
|
||||
* Fix deprecation warnings (c264879)
|
||||
* Bump nan (e4aea20)
|
||||
|
||||
1.6.1 / 2016-10-23
|
||||
==================
|
||||
|
||||
### Fixed
|
||||
* Make has_lib.sh work on BSD OSes (1727d66)
|
||||
|
||||
1.6.0 / 2016-10-16
|
||||
==================
|
||||
|
||||
* Support canvas.getBuffer('raw') (#819)
|
||||
|
||||
1.5.0 / 2016-09-11
|
||||
==================
|
||||
|
||||
* Crude PDF stream implementation (#781)
|
||||
* Update CI settings (#797)
|
||||
* Reduce some of the install warnings (#794)
|
||||
* Fix lineDash browser tests never finishing (#793)
|
||||
* Add issue template (#791)
|
||||
|
||||
1.4.0 / 2016-06-03
|
||||
==================
|
||||
|
||||
* Add support for evenodd fill rule (#762)
|
||||
|
||||
1.3.17 / 2016-06-03
|
||||
===================
|
||||
|
||||
* Removing redundant duplicate calls (#769)
|
||||
* Cleanup examples (#776)
|
||||
* Fix CanvasRenderingContext2D class name (#777)
|
||||
|
||||
1.3.16 / 2016-05-29
|
||||
===================
|
||||
|
||||
* Fix leak of data when streaming JPEG (#774)
|
||||
|
||||
1.3.15 / 2016-05-09
|
||||
===================
|
||||
|
||||
* Fix segfault in putImageData (#750)
|
||||
|
||||
1.3.14 / 2016-05-05
|
||||
===================
|
||||
|
||||
* Clamp JPEG buffer size (#739)
|
||||
|
||||
1.3.13 / 2016-05-01
|
||||
===================
|
||||
|
||||
* Bumb NAN version (#759)
|
||||
|
||||
1.3.12 / 2016-03-01
|
||||
===================
|
||||
|
||||
* Expose freetype version (#718)
|
||||
* Require new in constructor (#717)
|
||||
|
||||
1.3.11 / 2016-03-01
|
||||
===================
|
||||
|
||||
* Properly clamp quality in toDataURL (#728)
|
||||
* Strict mode (#719)
|
||||
|
||||
1.3.10 / 2016-02-07
|
||||
===================
|
||||
|
||||
* Fix segfault on node 0.10.x (#712)
|
||||
|
||||
1.3.9 / 2016-01-27
|
||||
==================
|
||||
|
||||
* Allow to unbind onload/onerror callback handlers (#706)
|
||||
|
||||
1.3.8 / 2016-01-22
|
||||
==================
|
||||
|
||||
* Cleanup build scripts and fix pangocairo detection (#701)
|
||||
|
||||
1.3.7 / 2016-01-13
|
||||
==================
|
||||
|
||||
* Don't unbind onload/onerror callbacks after invoking them (#615)
|
||||
|
||||
1.3.6 / 2016-01-06
|
||||
==================
|
||||
|
||||
* Allow optional arguments in `toDataURL` to be `undefined` and improve `toDataURL`'s spec compliance (#690)
|
||||
|
||||
1.3.5 / 2015-12-07
|
||||
==================
|
||||
|
||||
* Add image/jpeg support to `toDataUrl` (#685)
|
||||
|
||||
1.3.4 / 2015-11-21
|
||||
==================
|
||||
|
||||
* Upgrade nan to 2.1.0 (#671)
|
||||
|
||||
1.3.3 / 2015-11-21
|
||||
==================
|
||||
|
||||
* Fix compilation on Visual Studio 2015 (#670)
|
||||
|
||||
1.3.2 / 2015-11-18
|
||||
==================
|
||||
|
||||
* Fix incorrect Y offset and scaling for shadows (#669)
|
||||
|
||||
1.3.1 / 2015-11-09
|
||||
==================
|
||||
|
||||
* Wrap std::min calls in paranthesis to prevent macro expansion on windows (#660)
|
||||
|
||||
1.3.0 / 2015-10-26
|
||||
==================
|
||||
|
||||
* Expose ImageData constructor and make it more spec-compliant (#569)
|
||||
|
||||
1.2.11 / 2015-10-20
|
||||
===================
|
||||
|
||||
* Implement blur on images (#648)
|
||||
|
||||
1.2.10 / 2015-10-12
|
||||
===================
|
||||
|
||||
* Fix segfault in Canvas#jpegStream (#629)
|
||||
|
||||
1.2.9 / 2015-09-14
|
||||
==================
|
||||
|
||||
* Upgrade to Nan 2.x with support for iojs 3.x and Node.js 4.x (#622)
|
||||
|
||||
1.2.8 / 2015-08-30
|
||||
==================
|
||||
|
||||
* Clean up the tests (#612)
|
||||
* Replace CanvasPixelArray with Uint8ClampedArray to be API-compliant (#604)
|
||||
* Specify travis iojs versions (#611)
|
||||
|
||||
1.2.7 / 2015-07-29
|
||||
==================
|
||||
|
||||
* Avoid future reserved keyword (#592)
|
||||
|
||||
1.2.6 / 2015-07-29
|
||||
==================
|
||||
|
||||
* Fix the build on windows (#589)
|
||||
|
||||
1.2.5 / 2015-07-28
|
||||
==================
|
||||
|
||||
* Another npm release, since 1.2.4 was botched (see #596)
|
||||
|
||||
1.2.4 / 2015-07-23
|
||||
==================
|
||||
|
||||
* Point `homepage` and `repository` links to [`github.com/Automattic/node-canvas`][repo]
|
||||
* Fix Travis builds and Cairo include paths (thanks, Linus Unnebäck!)
|
||||
|
||||
1.2.3 / 2015-05-21
|
||||
==================
|
||||
|
||||
* Update TJ Holowaychuk's username in the readme
|
||||
* Fix segmentation fault in `Image::loadFromBuffer` when buffer is empty
|
||||
* Optimize getImageData()
|
||||
* package: add "license" attribute
|
||||
* package: update "nan" to v1.8.4
|
||||
* package: append `.git` to "repository" URL
|
||||
|
||||
1.2.2 / 2015-04-18
|
||||
==================
|
||||
|
||||
* Now works on io.js
|
||||
* Fix 'drawImage' scaling (the dimensions of the region that gets clipped also needs to be scaled).
|
||||
* Fix bug in StreamPNGSync
|
||||
|
||||
1.2.1 / 2015-02-10
|
||||
==================
|
||||
|
||||
* Use non-cairo 1.12 API for shadow blur
|
||||
|
||||
1.2.0 / 2015-01-31
|
||||
==================
|
||||
|
||||
* travis: drop support for node v0.6
|
||||
* Merge pull request #507 from salzhrani/iojs
|
||||
* io.js compatibility
|
||||
* Merge pull request #505 from woodcoder/shadow-blur
|
||||
* Fix issue with line width not being correct in stroked shadows.
|
||||
* Add another shadow/transform test.
|
||||
* Refactor setSourceRGBA to allow the context to be supplied.
|
||||
* Simple image shadow (no blurring or handling current transforms) based on image's alpha channel.
|
||||
* Test showing issue #133, that images don't have shadows.
|
||||
* The +1 on the offset seems to match the browser's output better, but I can't work out why it would be needed (unless it's pixel alignment related).
|
||||
* Make the shadow radius more accurately match the browser's, making use of sigma scale as used in SKIA: https://github.com/google/skia/blob/master/src/effects/SkBlurMask.cpp#L26.
|
||||
* Create a new image surface to render blurred shadows to, this means that vector formats like PDF will now render blurs.
|
||||
* Add recommended calls to flush and dirty buffer, as per http://www.cairographics.org/manual/cairo-Image-Surfaces.html#cairo-image-surface-get-data.
|
||||
* Add PDF button to test page to easily generate PDF version of the test image.
|
||||
* Fix to ensure shadowOffset is unaffected by the current transform.
|
||||
* New test illustrating that canvas implementation doesn't translate the shadowOffset.
|
||||
* Merge pull request #490 from AllYearbooks/master
|
||||
* Merge pull request #501 from motiz88/hsl-color
|
||||
* Code style + attribution. Also removed parseClipped() and commented out wrapInt (now wrap_int).
|
||||
* Added visual tests for hsl() and hsla() color parsing.
|
||||
* Fixed <number> handling in hsl/hsla color parser. parseNumber() was erroring out on numbers with long fractional parts.
|
||||
* hsl/hsla color parsing + rebeccapurple hsl() and hsla() color values are now supported, with corresponding unit tests. Also added rebeccapurple (from CSS Color Level 4) to the named color list.
|
||||
* float rather than int for drawImage arguments
|
||||
* with_pango to true and use fontconfig to load fonts
|
||||
* Merge pull request #399 from nulltask/fix/lighten
|
||||
* Merge pull request #465 from espadrine/master
|
||||
* Merge pull request #470 from tonylukasavage/patch-1
|
||||
* Add one-liner MacPorts install to docs
|
||||
* Offer SVG output.
|
||||
* Readme update: node-gyp.
|
||||
* Readme: fix subheading size
|
||||
* Readme: remove Gemnasium badge, use SVG for npm badge
|
||||
* Readme: add Travis-CI badge
|
||||
* change operator lighter to lighten
|
||||
|
||||
1.1.6 / 2014-08-01
|
||||
==================
|
||||
|
||||
* export canvas.CanvasPixelArray instead of canvas.PixelArray which is undefined
|
||||
* Glib version test into giflib exists test
|
||||
* Giflib 5.1
|
||||
* install: use an even older version of giflib (v4.1.6)
|
||||
* install: use an older version of giflib (v4.2.3)
|
||||
* install: install `giflib`
|
||||
* install: use more compatible sh syntax
|
||||
* travis: attempt to run the ./install script before testintg
|
||||
* travis: test node v0.6, v0.8, v0.10, and v0.11
|
||||
* Distinguish between 'add' and 'lighter'
|
||||
|
||||
1.1.5 / 2014-06-26
|
||||
==================
|
||||
|
||||
* Readme: remove Contributors section
|
||||
* Readme: update copyright
|
||||
* On Windows, copy required DLLs next to ".node" file (#442 @pandell)
|
||||
* Duplicate "msvc_settings" for "Debug" configuration
|
||||
* Remove unneeded #include <nan.h>
|
||||
* Use float constants to prevent double->float conversion warning
|
||||
* Ignore Visual C++ 2013 warnings (#441 @pandell)
|
||||
* Add algorithm include to CanvasRenderingContext2d.cc for std::min (#435 @kkoopa)
|
||||
* Updated NAN to 1.2.0 (#434 @kkoopa)
|
||||
|
||||
1.1.4 / 2014-06-08
|
||||
==================
|
||||
|
||||
* Fix compile error with Visual C++
|
||||
* Add support for the lineDash API
|
||||
* Update NAN
|
||||
* New V8 compatibility
|
||||
* Correctly limit bounds in PutImageData to prevent segment fault
|
||||
* Fix segfault when onload and onerror are not function
|
||||
* Add support for Node 0.11.9
|
||||
|
||||
1.1.3 / 2014-01-08
|
||||
==================
|
||||
|
||||
* Add CAIRO_FORMAT_INVALID
|
||||
* Readjust the amount of allocated memory
|
||||
* Fix argument index for filter parameter
|
||||
* Make has_lib.sh work properly on Debian 64bit
|
||||
|
||||
1.1.2 / 2013-10-31
|
||||
==================
|
||||
|
||||
* NAN dep upgrade, full node@<=0.11.8 compatibility
|
||||
* Use node::MakeCallback() instead of v8::Function::Call()
|
||||
* Improve nan location discovery
|
||||
* Fix enabling gif/jpeg options on Ubuntu 13.04
|
||||
|
||||
1.1.1 / 2013-10-09
|
||||
==================
|
||||
|
||||
* add better support for outdated versions of Cairo
|
||||
|
||||
1.1.0 / 2013-08-01
|
||||
==================
|
||||
|
||||
* add png compression options
|
||||
* add jpeg stream progressive mode option
|
||||
* fix resource leaks on read errors
|
||||
|
||||
1.0.4 / 2013-07-23
|
||||
==================
|
||||
|
||||
* 0.11.4+ compatibility using NAN
|
||||
* fix typo in context2d for imageSmoothingEnabled
|
||||
|
||||
1.0.3 / 2013-06-04
|
||||
==================
|
||||
|
||||
* add "nearest" and "bilinear" to patternQuality
|
||||
* fix fread() retval check (items not bytes)
|
||||
* removed unneeded private fields
|
||||
|
||||
1.0.2 / 2013-03-22
|
||||
==================
|
||||
|
||||
* add Context2d#imageSmoothingEnabled=
|
||||
|
||||
1.0.1 / 2013-02-25
|
||||
==================
|
||||
|
||||
* travis: test modern node versions
|
||||
* change the node-gyp build to use pkg-config
|
||||
|
||||
1.0.0 / 2013-01-16
|
||||
==================
|
||||
|
||||
* add conditional pango font support [Julian Viereck]
|
||||
* add `Canvas#{png,jpeg}Stream()` alias of create* legacy methods
|
||||
* add support for grayscale JPEGs
|
||||
* fix: explicitly cast the after work callback function to "uv_after_work_cb"
|
||||
* fix test server for express 3.x
|
||||
* fix: call cairo_surface_finish in ~Canvas when pdf
|
||||
* remove old 0.4.x binding support. Closes #197
|
||||
|
||||
0.13.1 / 2012-08-20
|
||||
==================
|
||||
|
||||
* fix cases where GIF_LIB_VERSION is not defined
|
||||
* fix auto-detection of optional libraries for OS X
|
||||
* fix Context2d::SetFont for pango when setting normal weight/style
|
||||
|
||||
0.13.0 / 2012-08-12
|
||||
==================
|
||||
|
||||
* add pango support [c-spencer]
|
||||
* add pango / png / jpeg gyp auto-detection [c-spencer]
|
||||
* add `.gifVersion` [tootallnate]
|
||||
* add `.jpegVersion` [tootallnate]
|
||||
* add moar gyp stuff [tootallnate]
|
||||
* remove wscript
|
||||
* fix `closure_destroy()` with cast for `AdjustAmountOfExternalAllocatedMemory()`
|
||||
|
||||
0.12.1 / 2012-06-29
|
||||
==================
|
||||
|
||||
* fix jpeg malloc Image issue. Closes #160 [c-spencer]
|
||||
* Improve Image mode API
|
||||
* Add clearData method to handle reassignment of src, and clean up mime data memory handling.
|
||||
* Improve how _data_len is managed and use to adjust memory, hide more of mime API behind cairo version conditional.
|
||||
* Add optional mime-data tracking to Image.
|
||||
* Refactor JPEG decoding into decodeJPEGIntoSurface
|
||||
|
||||
0.12.0 / 2012-05-02
|
||||
==================
|
||||
|
||||
* Added `textDrawingMode` context property [c-spencer]
|
||||
* Added additional TextMetrics properties [c-spencer]
|
||||
|
||||
0.11.3 / 2012-04-25
|
||||
==================
|
||||
|
||||
* Fixed `Image` memory leak. Closes #150
|
||||
* Fixed Context2d::hasShadow()
|
||||
|
||||
0.11.2 / 2012-04-12
|
||||
==================
|
||||
|
||||
* Fixed: pdf memory leak, free closure and surface in ~Canvas
|
||||
|
||||
0.11.1 / 2012-04-10
|
||||
==================
|
||||
|
||||
* Changed: renamed .nextPage() to .addPage()
|
||||
|
||||
0.11.0 / 2012-04-10
|
||||
==================
|
||||
|
||||
* Added quick PDF support
|
||||
* Added `Canvas#type` getter
|
||||
* Added ./examples/pdf-images.js
|
||||
* Added ./examples/multiple-page-pdf.js
|
||||
* Added ./examples/small-pdf.js
|
||||
|
||||
0.10.3 / 2012-02-27
|
||||
==================
|
||||
|
||||
* Fixed quadratic curve starting point for undefined path. Closes #155
|
||||
|
||||
0.10.2 / 2012-02-06
|
||||
==================
|
||||
|
||||
* Fixed: Context2d setters with invalid values ignored
|
||||
* Changed: replaced seek with `fstat()`
|
||||
|
||||
0.10.1 / 2012-01-31
|
||||
==================
|
||||
|
||||
* Added _/opt/local/lib_ to wscript [obarthel]
|
||||
* Added bounds checking to `rgba_to_string()` [obarthel]
|
||||
* Fixed cleanup in JPEG Image loading [obarthel]
|
||||
* Fixed missing CSS color table values [obarthel]
|
||||
|
||||
0.10.0 / 2012-01-18
|
||||
==================
|
||||
|
||||
* Added `ctx.createPattern()` [slaskis]
|
||||
|
||||
0.9.0 / 2012-01-13
|
||||
==================
|
||||
|
||||
* Added `createJPEGStream()` [Elijah Hamovitz]
|
||||
|
||||
0.8.3 / 2012-01-04
|
||||
==================
|
||||
|
||||
* Added support for libjpeg62-dev or libjpeg8-dev [wwlinx]
|
||||
|
||||
0.8.2 / 2011-12-14
|
||||
==================
|
||||
|
||||
* Fixed two memory leaks in context2d [Tharit]
|
||||
* Fixed `make test-server`
|
||||
|
||||
0.8.1 / 2011-10-31
|
||||
==================
|
||||
|
||||
* Added 0.5.x support [TooTallNate]
|
||||
* Fixed `measureText().width`. Closes #126
|
||||
|
||||
0.8.0 / 2011-10-28
|
||||
==================
|
||||
|
||||
* Added data uri support. Closes #49
|
||||
|
||||
0.7.3 / 2011-09-14
|
||||
==================
|
||||
|
||||
* Added better lineTo() / moveTo() exception messages
|
||||
|
||||
0.7.2 / 2011-08-30
|
||||
==================
|
||||
|
||||
* Changed: prefix some private methods with _
|
||||
|
||||
0.7.1 / 2011-08-25
|
||||
==================
|
||||
|
||||
* Added better image format detection
|
||||
* Added libpath options to waf configuration; this was necessary to correctly detect gif and jpeg support on FreeBSD
|
||||
|
||||
0.7.0 / 2011-07-12
|
||||
==================
|
||||
|
||||
* Added GIF support [Brian McKinney]
|
||||
|
||||
0.6.0 / 2011-06-04
|
||||
==================
|
||||
|
||||
* Added `Image#src=Buffer` support. Closes #91
|
||||
* Added `devDependencies`
|
||||
* Added `source-atop` test
|
||||
* Added _image-src.js_ example
|
||||
* Removed `V8::AdjustAmountOfExternalAllocatedMemory()` call from `toBuffer()`
|
||||
* Fixed v8 memory hint when resizing canvas [atomizer]
|
||||
|
||||
0.5.4 / 2011-04-20
|
||||
==================
|
||||
|
||||
* Added; special case of zero-width rectangle [atomizer]
|
||||
* Fixed; do not clamp arguments to integer values [atomizer]
|
||||
* Fixed; preserve current path during `fillRect()` and `strokeRect()` [atomizer]
|
||||
* Fixed; `restorePath()`: clear current path before appending [atomizer]
|
||||
|
||||
0.5.3 / 2011-04-11
|
||||
==================
|
||||
|
||||
* Clamp image bounds in `PixelArray::PixelArray()` [Marcello Bastea-Forte]
|
||||
|
||||
0.5.2 / 2011-04-09
|
||||
==================
|
||||
|
||||
* Changed; make `PNGStream` a real `Stream` [Marcello Bastea-Forte]
|
||||
|
||||
0.5.1 / 2011-03-16
|
||||
==================
|
||||
|
||||
* Fixed (kinda) `img.src=` error handling
|
||||
* Fixed; move closure.h down for malloc ref. Closes #80
|
||||
|
||||
0.5.0 / 2011-03-14
|
||||
==================
|
||||
|
||||
* Added several more operators (color-dodge, color-burn, difference, etc)
|
||||
* Performance; no longer re-allocating `closure->data` for each png write
|
||||
* Fixed freeing of `Context2d` states
|
||||
* Fixed text alignment / baseline [Olaf]
|
||||
* Fixed HandleScopes [Olaf]
|
||||
* Fixed small misc memory leaks
|
||||
* Fixed `Buffer` usage for node 0.4.x
|
||||
|
||||
0.4.3 / 2011-01-11
|
||||
==================
|
||||
|
||||
* Fixed font family dereferencing. Closes #72
|
||||
* Fixed; stripping of quotes from font-family before applying
|
||||
* Fixed duplicate textAlign getter
|
||||
* Removed sans-serif default of _Arial_
|
||||
|
||||
0.4.2 / 2010-12-28
|
||||
==================
|
||||
|
||||
* Fixed font size growing issue after successive calls. Closes #70
|
||||
|
||||
0.4.1 / 2010-12-18
|
||||
==================
|
||||
|
||||
* Fixed; toString() first argument of `{fill,stroke}Text()`. Closes #68
|
||||
|
||||
0.4.0 / 2010-12-12
|
||||
==================
|
||||
|
||||
* Added `drawImage()` with `Canvas` instance support. Closes #67
|
||||
|
||||
0.3.3 / 2010-11-30
|
||||
==================
|
||||
|
||||
* Added `CanvasRenderingContext2d#patternQuality` accessor, accepting _fast_, _good_, and _best_
|
||||
* Fixed; pre-multiply `putImageData()` components
|
||||
* Fixed; `PixelArray` data is not premultiplied
|
||||
|
||||
0.3.2 / 2010-11-26
|
||||
==================
|
||||
|
||||
* Added --profile option to config
|
||||
* Fixed `eio_custom` segfault(s). Closes #46
|
||||
* Fixed two named colors. Closes #62 [thanks noonat]
|
||||
* Fixed a few warnings
|
||||
* Fixed; freeing data in `Image::loadJPEG()` on failure
|
||||
* Fixed; include _jpeglib_ only when __HAVE_JPEG__
|
||||
* Fixed; using `strstr()` instead of `strnstr()`
|
||||
|
||||
0.3.1 / 2010-11-24
|
||||
==================
|
||||
|
||||
* Fixed; `Image` loading is sync until race-condition is resolved
|
||||
* Fixed; `Image::loadJPEG()` return status based on errno
|
||||
|
||||
0.3.0 / 2010-11-24
|
||||
==================
|
||||
|
||||
* Added arcTo(). Closes #11
|
||||
* Added c color parser, _./examples/ray.js_ is now twice as fast
|
||||
* Fixed `putImageData()` bug messing up rgba channels
|
||||
|
||||
0.2.1 / 2010-11-19
|
||||
==================
|
||||
|
||||
* Added image _resize_ example
|
||||
* Fixed canvas resizing via `{width,height}=`. Closes #57
|
||||
* Fixed `Canvas#getContext()`, caching the CanvasRenderingContext
|
||||
* Fixed async image loading (test server still messed)
|
||||
|
||||
0.2.0 / 2010-11-18
|
||||
==================
|
||||
|
||||
* Added jpeg `Image` support (when libjpeg is available)
|
||||
* Added _hsl_ / _hsla_ color support. [Tom Carden]
|
||||
|
||||
0.1.0 / 2010-11-17
|
||||
==================
|
||||
|
||||
* Added `Image`
|
||||
* Added `ImageData`
|
||||
* Added `PixelArray`
|
||||
* Added `CanvasRenderingContext2d#drawImage()`
|
||||
* Added `CanvasRenderingContext2d#getImageData()`
|
||||
* Added `CanvasRenderingContext2d#createImageData()`
|
||||
* Added kraken blur benchmark example
|
||||
* Added several new tests
|
||||
* Fixed instanceof checks for many c++ methods
|
||||
* Fixed test runner in firefox [Don Park]
|
||||
|
||||
0.0.8 / 2010-11-12
|
||||
==================
|
||||
|
||||
* Added `CanvasRenderingContext2d#drawImage()`
|
||||
* Fixed `free()` call missing stdlib
|
||||
* Fixed Image#{width,height} initialization to 0
|
||||
* Fixed; load image on non-LOADING state
|
||||
|
||||
0.0.7 / 2010-11-12
|
||||
==================
|
||||
|
||||
* Fixed _lighter_ for older versions of cairo
|
||||
|
||||
0.0.6 / 2010-11-12
|
||||
==================
|
||||
|
||||
* Added `Image`
|
||||
* Added conditional support for cairo 1.10.0 operators
|
||||
|
||||
0.0.5 / 2010-11-10
|
||||
==================
|
||||
|
||||
* Added custom port support to _test/server.js_
|
||||
* Added more global composite operator support
|
||||
* Added `Context2d#antialias=`
|
||||
* Added _voronoi_ example
|
||||
* Added -D__NDEBUG__ to default build
|
||||
* Added __BUFFER_DATA__ macro for backwards compat buffer data access [Don Park]
|
||||
* Fixed getter bug preventing patterns from being returned via `fillStyle` etc
|
||||
|
||||
* Fixed; __CAIRO_STATUS_NO_MEMORY___ on failed {re,m}alloc()
|
||||
* Fixed; free `Canvas::ToBuffer()` closure data
|
||||
|
||||
0.0.4 / 2010-11-09
|
||||
==================
|
||||
|
||||
* Bump to fix npm engine cache bug...
|
||||
|
||||
0.0.3 / 2010-11-09
|
||||
==================
|
||||
|
||||
* Added async `toDataURL()` support
|
||||
* Added async `toBuffer()` support
|
||||
* Removed buffer utils
|
||||
|
||||
0.0.2 / 2010-11-08
|
||||
==================
|
||||
|
||||
* Added shadow support (faster/better gaussian blur to come)
|
||||
* Added node v0.3 support [Don Park]
|
||||
* Added -O3 to build
|
||||
* Removed `Canvas#savePNG()` use `Canvas#createPNGStream()`
|
||||
|
||||
0.0.1 / 2010-11-04
|
||||
==================
|
||||
|
||||
* Initial release
|
||||
|
||||
[repo]: https://github.com/Automattic/node-canvas
|
||||
600
node_modules/canvas/Readme.md
generated
vendored
Normal file
600
node_modules/canvas/Readme.md
generated
vendored
Normal file
@@ -0,0 +1,600 @@
|
||||
# node-canvas
|
||||
|
||||

|
||||
[](http://badge.fury.io/js/canvas)
|
||||
|
||||
node-canvas is a [Cairo](http://cairographics.org/)-backed Canvas implementation for [Node.js](http://nodejs.org).
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ npm install canvas
|
||||
```
|
||||
|
||||
By default, binaries for macOS, Linux and Windows will be downloaded. If you want to build from source, use `npm install --build-from-source` and see the **Compiling** section below.
|
||||
|
||||
The minimum version of Node.js required is **6.0.0**.
|
||||
|
||||
### Compiling
|
||||
|
||||
If you don't have a supported OS or processor architecture, or you use `--build-from-source`, the module will be compiled on your system. This requires several dependencies, including Cairo and Pango.
|
||||
|
||||
For detailed installation information, see the [wiki](https://github.com/Automattic/node-canvas/wiki/_pages). One-line installation instructions for common OSes are below. Note that libgif/giflib, librsvg and libjpeg are optional and only required if you need GIF, SVG and JPEG support, respectively. Cairo v1.10.0 or later is required.
|
||||
|
||||
OS | Command
|
||||
----- | -----
|
||||
OS X | Using [Homebrew](https://brew.sh/):<br/>`brew install pkg-config cairo pango libpng jpeg giflib librsvg`
|
||||
Ubuntu | `sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev`
|
||||
Fedora | `sudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel`
|
||||
Solaris | `pkgin install cairo pango pkg-config xproto renderproto kbproto xextproto`
|
||||
OpenBSD | `doas pkg_add cairo pango png jpeg giflib`
|
||||
Windows | See the [wiki](https://github.com/Automattic/node-canvas/wiki/Installation:-Windows)
|
||||
Others | See the [wiki](https://github.com/Automattic/node-canvas/wiki)
|
||||
|
||||
**Mac OS X v10.11+:** If you have recently updated to Mac OS X v10.11+ and are experiencing trouble when compiling, run the following command: `xcode-select --install`. Read more about the problem [on Stack Overflow](http://stackoverflow.com/a/32929012/148072).
|
||||
If you have xcode 10.0 or higher installed, in order to build from source you need NPM 6.4.1 or higher.
|
||||
|
||||
## Quick Example
|
||||
|
||||
```javascript
|
||||
const { createCanvas, loadImage } = require('canvas')
|
||||
const canvas = createCanvas(200, 200)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
// Write "Awesome!"
|
||||
ctx.font = '30px Impact'
|
||||
ctx.rotate(0.1)
|
||||
ctx.fillText('Awesome!', 50, 100)
|
||||
|
||||
// Draw line under text
|
||||
var text = ctx.measureText('Awesome!')
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
|
||||
ctx.beginPath()
|
||||
ctx.lineTo(50, 102)
|
||||
ctx.lineTo(50 + text.width, 102)
|
||||
ctx.stroke()
|
||||
|
||||
// Draw cat with lime helmet
|
||||
loadImage('examples/images/lime-cat.jpg').then((image) => {
|
||||
ctx.drawImage(image, 50, 0, 70, 70)
|
||||
|
||||
console.log('<img src="' + canvas.toDataURL() + '" />')
|
||||
})
|
||||
```
|
||||
|
||||
## Upgrading from 1.x to 2.x
|
||||
|
||||
See the [changelog](https://github.com/Automattic/node-canvas/blob/master/CHANGELOG.md) for a guide to upgrading from 1.x to 2.x.
|
||||
|
||||
For version 1.x documentation, see [the v1.x branch](https://github.com/Automattic/node-canvas/tree/v1.x).
|
||||
|
||||
## Documentation
|
||||
|
||||
This project is an implementation of the Web Canvas API and implements that API as closely as possible. For API documentation, please visit [Mozilla Web Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). (See [Compatibility Status](https://github.com/Automattic/node-canvas/wiki/Compatibility-Status) for the current API compliance.) All utility methods and non-standard APIs are documented below.
|
||||
|
||||
### Utility methods
|
||||
|
||||
* [createCanvas()](#createcanvas)
|
||||
* [createImageData()](#createimagedata)
|
||||
* [loadImage()](#loadimage)
|
||||
* [registerFont()](#registerfont)
|
||||
|
||||
### Non-standard APIs
|
||||
|
||||
* [Image#src](#imagesrc)
|
||||
* [Image#dataMode](#imagedatamode)
|
||||
* [Canvas#toBuffer()](#canvastobuffer)
|
||||
* [Canvas#createPNGStream()](#canvascreatepngstream)
|
||||
* [Canvas#createJPEGStream()](#canvascreatejpegstream)
|
||||
* [Canvas#createPDFStream()](#canvascreatepdfstream)
|
||||
* [Canvas#toDataURL()](#canvastodataurl)
|
||||
* [CanvasRenderingContext2D#patternQuality](#canvasrenderingcontext2dpatternquality)
|
||||
* [CanvasRenderingContext2D#quality](#canvasrenderingcontext2dquality)
|
||||
* [CanvasRenderingContext2D#textDrawingMode](#canvasrenderingcontext2dtextdrawingmode)
|
||||
* [CanvasRenderingContext2D#globalCompositeOperator = 'saturate'](#canvasrenderingcontext2dglobalcompositeoperator--saturate)
|
||||
* [CanvasRenderingContext2D#antialias](#canvasrenderingcontext2dantialias)
|
||||
|
||||
### createCanvas()
|
||||
|
||||
> ```ts
|
||||
> createCanvas(width: number, height: number, type?: 'PDF'|'SVG') => Canvas
|
||||
> ```
|
||||
|
||||
Creates a Canvas instance. This method works in both Node.js and Web browsers, where there is no Canvas constructor. (See `browser.js` for the implementation that runs in browsers.)
|
||||
|
||||
```js
|
||||
const { createCanvas } = require('canvas')
|
||||
const mycanvas = createCanvas(200, 200)
|
||||
const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" section
|
||||
```
|
||||
|
||||
### createImageData()
|
||||
|
||||
> ```ts
|
||||
> createImageData(width: number, height: number) => ImageData
|
||||
> createImageData(data: Uint8ClampedArray, width: number, height?: number) => ImageData
|
||||
> // for alternative pixel formats:
|
||||
> createImageData(data: Uint16Array, width: number, height?: number) => ImageData
|
||||
> ```
|
||||
|
||||
Creates an ImageData instance. This method works in both Node.js and Web browsers.
|
||||
|
||||
```js
|
||||
const { createImageData } = require('canvas')
|
||||
const width = 20, height = 20
|
||||
const arraySize = width * height * 4
|
||||
const mydata = createImageData(new Uint8ClampedArray(arraySize), width)
|
||||
```
|
||||
|
||||
### loadImage()
|
||||
|
||||
> ```ts
|
||||
> loadImage() => Promise<Image>
|
||||
> ```
|
||||
|
||||
Convenience method for loading images. This method works in both Node.js and Web browsers.
|
||||
|
||||
```js
|
||||
const { loadImage } = require('canvas')
|
||||
const myimg = loadImage('http://server.com/image.png')
|
||||
|
||||
myimg.then(() => {
|
||||
// do something with image
|
||||
}).catch(err => {
|
||||
console.log('oh no!', err)
|
||||
})
|
||||
|
||||
// or with async/await:
|
||||
const myimg = await loadImage('http://server.com/image.png')
|
||||
// do something with image
|
||||
```
|
||||
|
||||
### registerFont()
|
||||
|
||||
> ```ts
|
||||
> registerFont(path: string, { family: string, weight?: string, style?: string }) => void
|
||||
> ```
|
||||
|
||||
To use a font file that is not installed as a system font, use `registerFont()` to register the font with Canvas. *This must be done before the Canvas is created.*
|
||||
|
||||
```js
|
||||
const { registerFont, createCanvas } = require('canvas')
|
||||
registerFont('comicsans.ttf', { family: 'Comic Sans' })
|
||||
|
||||
const canvas = createCanvas(500, 500)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
ctx.font = '12px "Comic Sans"'
|
||||
ctx.fillText('Everyone hates this font :(', 250, 10)
|
||||
```
|
||||
|
||||
The second argument is an object with properties that resemble the CSS properties that are specified in `@font-face` rules. You must specify at least `family`. `weight`, and `style` are optional and default to `'normal'`.
|
||||
|
||||
### Image#src
|
||||
|
||||
> ```ts
|
||||
> img.src: string|Buffer
|
||||
> ```
|
||||
|
||||
As in browsers, `img.src` can be set to a `data:` URI or a remote URL. In addition, node-canvas allows setting `src` to a local file path or `Buffer` instance.
|
||||
|
||||
```javascript
|
||||
const { Image } = require('canvas')
|
||||
|
||||
// From a buffer:
|
||||
fs.readFile('images/squid.png', (err, squid) => {
|
||||
if (err) throw err
|
||||
const img = new Image()
|
||||
img.onload = () => ctx.drawImage(img, 0, 0)
|
||||
img.onerror = err => { throw err }
|
||||
img.src = squid
|
||||
})
|
||||
|
||||
// From a local file path:
|
||||
const img = new Image()
|
||||
img.onload = () => ctx.drawImage(img, 0, 0)
|
||||
img.onerror = err => { throw err }
|
||||
img.src = 'images/squid.png'
|
||||
|
||||
// From a remote URL:
|
||||
img.src = 'http://picsum.photos/200/300'
|
||||
// ... as above
|
||||
|
||||
// From a `data:` URI:
|
||||
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
|
||||
// ... as above
|
||||
```
|
||||
|
||||
*Note: In some cases, `img.src=` is currently synchronous. However, you should always use `img.onload` and `img.onerror`, as we intend to make `img.src=` always asynchronous as it is in browsers. See https://github.com/Automattic/node-canvas/issues/1007.*
|
||||
|
||||
### Image#dataMode
|
||||
|
||||
> ```ts
|
||||
> img.dataMode: number
|
||||
> ```
|
||||
|
||||
Applies to JPEG images drawn to PDF canvases only.
|
||||
|
||||
Setting `img.dataMode = Image.MODE_MIME` or `Image.MODE_MIME|Image.MODE_IMAGE` enables MIME data tracking of images. When MIME data is tracked, PDF canvases can embed JPEGs directly into the output, rather than re-encoding into PNG. This can drastically reduce filesize and speed up rendering.
|
||||
|
||||
```javascript
|
||||
const { Image, createCanvas } = require('canvas')
|
||||
const canvas = createCanvas(w, h, 'pdf')
|
||||
const img = new Image()
|
||||
img.dataMode = Image.MODE_IMAGE // Only image data tracked
|
||||
img.dataMode = Image.MODE_MIME // Only mime data tracked
|
||||
img.dataMode = Image.MODE_MIME | Image.MODE_IMAGE // Both are tracked
|
||||
```
|
||||
|
||||
If working with a non-PDF canvas, image data *must* be tracked; otherwise the output will be junk.
|
||||
|
||||
Enabling mime data tracking has no benefits (only a slow down) unless you are generating a PDF.
|
||||
|
||||
### Canvas#toBuffer()
|
||||
|
||||
> ```ts
|
||||
> canvas.toBuffer((err: Error|null, result: Buffer) => void, mimeType?: string, config?: any) => void
|
||||
> canvas.toBuffer(mimeType?: string, config?: any) => Buffer
|
||||
> ```
|
||||
|
||||
Creates a [`Buffer`](https://nodejs.org/api/buffer.html) object representing the image contained in the canvas.
|
||||
|
||||
* **callback** If provided, the buffer will be provided in the callback instead of being returned by the function. Invoked with an error as the first argument if encoding failed, or the resulting buffer as the second argument if it succeeded. Not supported for mimeType `raw` or for PDF or SVG canvases.
|
||||
* **mimeType** A string indicating the image format. Valid options are `image/png`, `image/jpeg` (if node-canvas was built with JPEG support), `raw` (unencoded data in BGRA order on little-endian (most) systems, ARGB on big-endian systems; top-to-bottom), `application/pdf` (for PDF canvases) and `image/svg+xml` (for SVG canvases). Defaults to `image/png` for image canvases, or the corresponding type for PDF or SVG canvas.
|
||||
* **config**
|
||||
* For `image/jpeg`, an object specifying the quality (0 to 1), if progressive compression should be used and/or if chroma subsampling should be used: `{quality: 0.75, progressive: false, chromaSubsampling: true}`. All properties are optional.
|
||||
|
||||
* For `image/png`, an object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only), the the background palette index (indexed PNGs only) and/or the resolution (ppi): `{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}`. All properties are optional.
|
||||
|
||||
Note that the PNG format encodes the resolution in pixels per meter, so if you specify `96`, the file will encode 3780 ppm (~96.01 ppi). The resolution is undefined by default to match common browser behavior.
|
||||
|
||||
* For `application/pdf`, an object specifying optional document metadata: `{title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}`. All properties are optional and default to `undefined`, except for `creationDate`, which defaults to the current date. *Adding metadata requires Cairo 1.16.0 or later.*
|
||||
|
||||
For a description of these properties, see page 550 of [PDF 32000-1:2008](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf).
|
||||
|
||||
Note that there is no standard separator for `keywords`. A space is recommended because it is in common use by other applications, and Cairo will enclose the list of keywords in quotes if a comma or semicolon is used.
|
||||
|
||||
**Return value**
|
||||
|
||||
If no callback is provided, a [`Buffer`](https://nodejs.org/api/buffer.html). If a callback is provided, none.
|
||||
|
||||
#### Examples
|
||||
|
||||
```js
|
||||
// Default: buf contains a PNG-encoded image
|
||||
const buf = canvas.toBuffer()
|
||||
|
||||
// PNG-encoded, zlib compression level 3 for faster compression but bigger files, no filtering
|
||||
const buf2 = canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE })
|
||||
|
||||
// JPEG-encoded, 50% quality
|
||||
const buf3 = canvas.toBuffer('image/jpeg', { quality: 0.5 })
|
||||
|
||||
// Asynchronous PNG
|
||||
canvas.toBuffer((err, buf) => {
|
||||
if (err) throw err // encoding failed
|
||||
// buf is PNG-encoded image
|
||||
})
|
||||
|
||||
canvas.toBuffer((err, buf) => {
|
||||
if (err) throw err // encoding failed
|
||||
// buf is JPEG-encoded image at 95% quality
|
||||
}, 'image/jpeg', { quality: 0.95 })
|
||||
|
||||
// BGRA pixel values, native-endian
|
||||
const buf4 = canvas.toBuffer('raw')
|
||||
const { stride, width } = canvas
|
||||
// In memory, this is `canvas.height * canvas.stride` bytes long.
|
||||
// The top row of pixels, in BGRA order on little-endian hardware,
|
||||
// left-to-right, is:
|
||||
const topPixelsBGRALeftToRight = buf4.slice(0, width * 4)
|
||||
// And the third row is:
|
||||
const row3 = buf4.slice(2 * stride, 2 * stride + width * 4)
|
||||
|
||||
// SVG and PDF canvases
|
||||
const myCanvas = createCanvas(w, h, 'pdf')
|
||||
myCanvas.toBuffer() // returns a buffer containing a PDF-encoded canvas
|
||||
// With optional metadata:
|
||||
myCanvas.toBuffer('application/pdf', {
|
||||
title: 'my picture',
|
||||
keywords: 'node.js demo cairo',
|
||||
creationDate: new Date()
|
||||
})
|
||||
```
|
||||
|
||||
### Canvas#createPNGStream()
|
||||
|
||||
> ```ts
|
||||
> canvas.createPNGStream(config?: any) => ReadableStream
|
||||
> ```
|
||||
|
||||
Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits PNG-encoded data.
|
||||
|
||||
* `config` An object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only) and/or the background palette index (indexed PNGs only): `{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}`. All properties are optional.
|
||||
|
||||
#### Examples
|
||||
|
||||
```javascript
|
||||
const fs = require('fs')
|
||||
const out = fs.createWriteStream(__dirname + '/test.png')
|
||||
const stream = canvas.createPNGStream()
|
||||
stream.pipe(out)
|
||||
out.on('finish', () => console.log('The PNG file was created.'))
|
||||
```
|
||||
|
||||
To encode indexed PNGs from canvases with `pixelFormat: 'A8'` or `'A1'`, provide an options object:
|
||||
|
||||
```js
|
||||
const palette = new Uint8ClampedArray([
|
||||
//r g b a
|
||||
0, 50, 50, 255, // index 1
|
||||
10, 90, 90, 255, // index 2
|
||||
127, 127, 255, 255
|
||||
// ...
|
||||
])
|
||||
canvas.createPNGStream({
|
||||
palette: palette,
|
||||
backgroundIndex: 0 // optional, defaults to 0
|
||||
})
|
||||
```
|
||||
|
||||
### Canvas#createJPEGStream()
|
||||
|
||||
> ```ts
|
||||
> canvas.createJPEGStream(config?: any) => ReadableStream
|
||||
> ```
|
||||
|
||||
Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits JPEG-encoded data.
|
||||
|
||||
*Note: At the moment, `createJPEGStream()` is synchronous under the hood. That is, it runs in the main thread, not in the libuv threadpool.*
|
||||
|
||||
* `config` an object specifying the quality (0 to 1), if progressive compression should be used and/or if chroma subsampling should be used: `{quality: 0.75, progressive: false, chromaSubsampling: true}`. All properties are optional.
|
||||
|
||||
#### Examples
|
||||
|
||||
```javascript
|
||||
const fs = require('fs')
|
||||
const out = fs.createWriteStream(__dirname + '/test.jpeg')
|
||||
const stream = canvas.createJPEGStream()
|
||||
stream.pipe(out)
|
||||
out.on('finish', () => console.log('The JPEG file was created.'))
|
||||
|
||||
// Disable 2x2 chromaSubsampling for deeper colors and use a higher quality
|
||||
const stream = canvas.createJPEGStream({
|
||||
quality: 0.95,
|
||||
chromaSubsampling: false
|
||||
})
|
||||
```
|
||||
|
||||
### Canvas#createPDFStream()
|
||||
|
||||
> ```ts
|
||||
> canvas.createPDFStream(config?: any) => ReadableStream
|
||||
> ```
|
||||
|
||||
* `config` an object specifying optional document metadata: `{title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}`. See `toBuffer()` for more information. *Adding metadata requires Cairo 1.16.0 or later.*
|
||||
|
||||
Applies to PDF canvases only. Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits the encoded PDF. `canvas.toBuffer()` also produces an encoded PDF, but `createPDFStream()` can be used to reduce memory usage.
|
||||
|
||||
### Canvas#toDataURL()
|
||||
|
||||
This is a standard API, but several non-standard calls are supported. The full list of supported calls is:
|
||||
|
||||
```js
|
||||
dataUrl = canvas.toDataURL() // defaults to PNG
|
||||
dataUrl = canvas.toDataURL('image/png')
|
||||
dataUrl = canvas.toDataURL('image/jpeg')
|
||||
dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1
|
||||
canvas.toDataURL((err, png) => { }) // defaults to PNG
|
||||
canvas.toDataURL('image/png', (err, png) => { })
|
||||
canvas.toDataURL('image/jpeg', (err, jpeg) => { }) // sync JPEG is not supported
|
||||
canvas.toDataURL('image/jpeg', {...opts}, (err, jpeg) => { }) // see Canvas#createJPEGStream for valid options
|
||||
canvas.toDataURL('image/jpeg', quality, (err, jpeg) => { }) // spec-following; quality from 0 to 1
|
||||
```
|
||||
|
||||
### CanvasRenderingContext2D#patternQuality
|
||||
|
||||
> ```ts
|
||||
> context.patternQuality: 'fast'|'good'|'best'|'nearest'|'bilinear'
|
||||
> ```
|
||||
|
||||
Defaults to `'good'`. Affects pattern (gradient, image, etc.) rendering quality.
|
||||
|
||||
### CanvasRenderingContext2D#quality
|
||||
|
||||
> ```ts
|
||||
> context.quality: 'fast'|'good'|'best'|'nearest'|'bilinear'
|
||||
> ```
|
||||
|
||||
Defaults to `'good'`. Like `patternQuality`, but applies to transformations affecting more than just patterns.
|
||||
|
||||
### CanvasRenderingContext2D#textDrawingMode
|
||||
|
||||
> ```ts
|
||||
> context.textDrawingMode: 'path'|'glyph'
|
||||
> ```
|
||||
|
||||
Defaults to `'path'`. The effect depends on the canvas type:
|
||||
|
||||
* **Standard (image)** `glyph` and `path` both result in rasterized text. Glyph mode is faster than `path`, but may result in lower-quality text, especially when rotated or translated.
|
||||
|
||||
* **PDF** `glyph` will embed text instead of paths into the PDF. This is faster to encode, faster to open with PDF viewers, yields a smaller file size and makes the text selectable. The subset of the font needed to render the glyphs will be embedded in the PDF. This is usually the mode you want to use with PDF canvases.
|
||||
|
||||
* **SVG** `glyph` does *not* cause `<text>` elements to be produced as one might expect ([cairo bug](https://gitlab.freedesktop.org/cairo/cairo/issues/253)). Rather, `glyph` will create a `<defs>` section with a `<symbol>` for each glyph, then those glyphs be reused via `<use>` elements. `path` mode creates a `<path>` element for each text string. `glyph` mode is faster and yields a smaller file size.
|
||||
|
||||
In `glyph` mode, `ctx.strokeText()` and `ctx.fillText()` behave the same (aside from using the stroke and fill style, respectively).
|
||||
|
||||
This property is tracked as part of the canvas state in save/restore.
|
||||
|
||||
### CanvasRenderingContext2D#globalCompositeOperation = 'saturate'
|
||||
|
||||
In addition to all of the standard global composite operations defined by the Canvas specification, the ['saturate'](https://www.cairographics.org/operators/#saturate) operation is also available.
|
||||
|
||||
### CanvasRenderingContext2D#antialias
|
||||
|
||||
> ```ts
|
||||
> context.antialias: 'default'|'none'|'gray'|'subpixel'
|
||||
> ```
|
||||
|
||||
Sets the anti-aliasing mode.
|
||||
|
||||
## PDF Output Support
|
||||
|
||||
node-canvas can create PDF documents instead of images. The canvas type must be set when creating the canvas as follows:
|
||||
|
||||
```js
|
||||
const canvas = createCanvas(200, 500, 'pdf')
|
||||
```
|
||||
|
||||
An additional method `.addPage()` is then available to create multiple page PDFs:
|
||||
|
||||
```js
|
||||
// On first page
|
||||
ctx.font = '22px Helvetica'
|
||||
ctx.fillText('Hello World', 50, 80)
|
||||
|
||||
ctx.addPage()
|
||||
// Now on second page
|
||||
ctx.font = '22px Helvetica'
|
||||
ctx.fillText('Hello World 2', 50, 80)
|
||||
|
||||
canvas.toBuffer() // returns a PDF file
|
||||
canvas.createPDFStream() // returns a ReadableStream that emits a PDF
|
||||
// With optional document metadata (requires Cairo 1.16.0):
|
||||
canvas.toBuffer('application/pdf', {
|
||||
title: 'my picture',
|
||||
keywords: 'node.js demo cairo',
|
||||
creationDate: new Date()
|
||||
})
|
||||
```
|
||||
|
||||
It is also possible to create pages with different sizes by passing `width` and `height` to the `.addPage()` method:
|
||||
|
||||
```js
|
||||
ctx.font = '22px Helvetica'
|
||||
ctx.fillText('Hello World', 50, 80)
|
||||
ctx.addPage(400, 800)
|
||||
|
||||
ctx.fillText('Hello World 2', 50, 80)
|
||||
```
|
||||
|
||||
See also:
|
||||
|
||||
* [Image#dataMode](#imagedatamode) for embedding JPEGs in PDFs
|
||||
* [Canvas#createPDFStream()](#canvascreatepdfstream) for creating PDF streams
|
||||
* [CanvasRenderingContext2D#textDrawingMode](#canvasrenderingcontext2dtextdrawingmode)
|
||||
for embedding text instead of paths
|
||||
|
||||
## SVG Output Support
|
||||
|
||||
node-canvas can create SVG documents instead of images. The canvas type must be set when creating the canvas as follows:
|
||||
|
||||
```js
|
||||
const canvas = createCanvas(200, 500, 'svg')
|
||||
// Use the normal primitives.
|
||||
fs.writeFileSync('out.svg', canvas.toBuffer())
|
||||
```
|
||||
|
||||
## SVG Image Support
|
||||
|
||||
If librsvg is available when node-canvas is installed, node-canvas can render SVG images to your canvas context. This currently works by rasterizing the SVG image (i.e. drawing an SVG image to an SVG canvas will not preserve the SVG data).
|
||||
|
||||
```js
|
||||
const img = new Image()
|
||||
img.onload = () => ctx.drawImage(img, 0, 0)
|
||||
img.onerror = err => { throw err }
|
||||
img.src = './example.svg'
|
||||
```
|
||||
|
||||
## Image pixel formats (experimental)
|
||||
|
||||
node-canvas has experimental support for additional pixel formats, roughly following the [Canvas color space proposal](https://github.com/WICG/canvas-color-space/blob/master/CanvasColorSpaceProposal.md).
|
||||
|
||||
```js
|
||||
const canvas = createCanvas(200, 200)
|
||||
const ctx = canvas.getContext('2d', { pixelFormat: 'A8' })
|
||||
```
|
||||
|
||||
By default, canvases are created in the `RGBA32` format, which corresponds to the native HTML Canvas behavior. Each pixel is 32 bits. The JavaScript APIs that involve pixel data (`getImageData`, `putImageData`) store the colors in the order {red, green, blue, alpha} without alpha pre-multiplication. (The C++ API stores the colors in the order {alpha, red, green, blue} in native-[endian](https://en.wikipedia.org/wiki/Endianness) ordering, with alpha pre-multiplication.)
|
||||
|
||||
These additional pixel formats have experimental support:
|
||||
|
||||
* `RGB24` Like `RGBA32`, but the 8 alpha bits are always opaque. This format is always used if the `alpha` context attribute is set to false (i.e. `canvas.getContext('2d', {alpha: false})`). This format can be faster than `RGBA32` because transparency does not need to be calculated.
|
||||
* `A8` Each pixel is 8 bits. This format can either be used for creating grayscale images (treating each byte as an alpha value), or for creating indexed PNGs (treating each byte as a palette index) (see [the example using alpha values with `fillStyle`](examples/indexed-png-alpha.js) and [the example using `imageData`](examples/indexed-png-image-data.js)).
|
||||
* `RGB16_565` Each pixel is 16 bits, with red in the upper 5 bits, green in the middle 6 bits, and blue in the lower 5 bits, in native platform endianness. Some hardware devices and frame buffers use this format. Note that PNG does not support this format; when creating a PNG, the image will be converted to 24-bit RGB. This format is thus suboptimal for generating PNGs. `ImageData` instances for this mode use a `Uint16Array` instead of a `Uint8ClampedArray`.
|
||||
* `A1` Each pixel is 1 bit, and pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianness of the
|
||||
platform: on a little-endian machine, the first pixel is the least-significant bit. This format can be used for creating single-color images. *Support for this format is incomplete, see note below.*
|
||||
* `RGB30` Each pixel is 30 bits, with red in the upper 10, green in the middle 10, and blue in the lower 10. (Requires Cairo 1.12 or later.) *Support for this format is incomplete, see note below.*
|
||||
|
||||
Notes and caveats:
|
||||
|
||||
* Using a non-default format can affect the behavior of APIs that involve pixel data:
|
||||
|
||||
* `context2d.createImageData` The size of the array returned depends on the number of bit per pixel for the underlying image data format, per the above descriptions.
|
||||
* `context2d.getImageData` The format of the array returned depends on the underlying image mode, per the above descriptions. Be aware of platform endianness, which can be determined using node.js's [`os.endianness()`](https://nodejs.org/api/os.html#os_os_endianness)
|
||||
function.
|
||||
* `context2d.putImageData` As above.
|
||||
|
||||
* `A1` and `RGB30` do not yet support `getImageData` or `putImageData`. Have a use case and/or opinion on working with these formats? Open an issue and let us know! (See #935.)
|
||||
|
||||
* `A1`, `A8`, `RGB30` and `RGB16_565` with shadow blurs may crash or not render properly.
|
||||
|
||||
* The `ImageData(width, height)` and `ImageData(Uint8ClampedArray, width)` constructors assume 4 bytes per pixel. To create an `ImageData` instance with a different number of bytes per pixel, use `new ImageData(new Uint8ClampedArray(size), width, height)` or `new ImageData(new Uint16ClampedArray(size), width, height)`.
|
||||
|
||||
## Testing
|
||||
|
||||
First make sure you've built the latest version. Get all the deps you need (see [compiling](#compiling) above), and run:
|
||||
|
||||
```
|
||||
npm install --build-from-source
|
||||
```
|
||||
|
||||
For visual tests: `npm run test-server` and point your browser to http://localhost:4000.
|
||||
|
||||
For unit tests: `npm run test`.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Benchmarks live in the `benchmarks` directory.
|
||||
|
||||
## Examples
|
||||
|
||||
Examples line in the `examples` directory. Most produce a png image of the same name, and others such as *live-clock.js* launch an HTTP server to be viewed in the browser.
|
||||
|
||||
## Original Authors
|
||||
|
||||
- TJ Holowaychuk ([tj](http://github.com/tj))
|
||||
- Nathan Rajlich ([TooTallNate](http://github.com/TooTallNate))
|
||||
- Rod Vagg ([rvagg](http://github.com/rvagg))
|
||||
- Juriy Zaytsev ([kangax](http://github.com/kangax))
|
||||
|
||||
## License
|
||||
|
||||
### node-canvas
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2010 LearnBoost, and contributors <dev@learnboost.com>
|
||||
|
||||
Copyright (c) 2014 Automattic, Inc and contributors <dev@automattic.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.
|
||||
|
||||
### BMP parser
|
||||
|
||||
See [license](src/bmp/LICENSE.md)
|
||||
222
node_modules/canvas/binding.gyp
generated
vendored
Normal file
222
node_modules/canvas/binding.gyp
generated
vendored
Normal file
@@ -0,0 +1,222 @@
|
||||
{
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'variables': {
|
||||
'GTK_Root%': 'C:/GTK', # Set the location of GTK all-in-one bundle
|
||||
'with_jpeg%': 'false',
|
||||
'with_gif%': 'false',
|
||||
'with_rsvg%': 'false',
|
||||
'variables': { # Nest jpeg_root to evaluate it before with_jpeg
|
||||
'jpeg_root%': '<!(node ./util/win_jpeg_lookup)'
|
||||
},
|
||||
'jpeg_root%': '<(jpeg_root)', # Take value of nested variable
|
||||
'conditions': [
|
||||
['jpeg_root==""', {
|
||||
'with_jpeg%': 'false'
|
||||
}, {
|
||||
'with_jpeg%': 'true'
|
||||
}]
|
||||
]
|
||||
}
|
||||
}, { # 'OS!="win"'
|
||||
'variables': {
|
||||
'with_jpeg%': '<!(node ./util/has_lib.js jpeg)',
|
||||
'with_gif%': '<!(node ./util/has_lib.js gif)',
|
||||
'with_rsvg%': '<!(node ./util/has_lib.js rsvg)'
|
||||
}
|
||||
}]
|
||||
],
|
||||
'targets': [
|
||||
{
|
||||
'target_name': 'canvas-postbuild',
|
||||
'dependencies': ['canvas'],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'copies': [{
|
||||
'destination': '<(PRODUCT_DIR)',
|
||||
'files': [
|
||||
'<(GTK_Root)/bin/zlib1.dll',
|
||||
'<(GTK_Root)/bin/libintl-8.dll',
|
||||
'<(GTK_Root)/bin/libpng14-14.dll',
|
||||
'<(GTK_Root)/bin/libpangocairo-1.0-0.dll',
|
||||
'<(GTK_Root)/bin/libpango-1.0-0.dll',
|
||||
'<(GTK_Root)/bin/libpangoft2-1.0-0.dll',
|
||||
'<(GTK_Root)/bin/libpangowin32-1.0-0.dll',
|
||||
'<(GTK_Root)/bin/libcairo-2.dll',
|
||||
'<(GTK_Root)/bin/libfontconfig-1.dll',
|
||||
'<(GTK_Root)/bin/libfreetype-6.dll',
|
||||
'<(GTK_Root)/bin/libglib-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libgobject-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libgmodule-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libgthread-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libexpat-1.dll'
|
||||
]
|
||||
}]
|
||||
}]
|
||||
]
|
||||
},
|
||||
{
|
||||
'target_name': 'canvas',
|
||||
'include_dirs': ["<!(node -e \"require('nan')\")"],
|
||||
'sources': [
|
||||
'src/backend/Backend.cc',
|
||||
'src/backend/ImageBackend.cc',
|
||||
'src/backend/PdfBackend.cc',
|
||||
'src/backend/SvgBackend.cc',
|
||||
'src/bmp/BMPParser.cc',
|
||||
'src/Backends.cc',
|
||||
'src/Canvas.cc',
|
||||
'src/CanvasGradient.cc',
|
||||
'src/CanvasPattern.cc',
|
||||
'src/CanvasRenderingContext2d.cc',
|
||||
'src/closure.cc',
|
||||
'src/color.cc',
|
||||
'src/Image.cc',
|
||||
'src/ImageData.cc',
|
||||
'src/init.cc',
|
||||
'src/register_font.cc'
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'libraries': [
|
||||
'-l<(GTK_Root)/lib/cairo.lib',
|
||||
'-l<(GTK_Root)/lib/libpng.lib',
|
||||
'-l<(GTK_Root)/lib/pangocairo-1.0.lib',
|
||||
'-l<(GTK_Root)/lib/pango-1.0.lib',
|
||||
'-l<(GTK_Root)/lib/freetype.lib',
|
||||
'-l<(GTK_Root)/lib/glib-2.0.lib',
|
||||
'-l<(GTK_Root)/lib/gobject-2.0.lib'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<(GTK_Root)/include',
|
||||
'<(GTK_Root)/include/cairo',
|
||||
'<(GTK_Root)/include/pango-1.0',
|
||||
'<(GTK_Root)/include/glib-2.0',
|
||||
'<(GTK_Root)/include/freetype2',
|
||||
'<(GTK_Root)/lib/glib-2.0/include'
|
||||
],
|
||||
'defines': [
|
||||
'_USE_MATH_DEFINES' # for M_PI
|
||||
],
|
||||
'configurations': {
|
||||
'Debug': {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
'WarningLevel': 4,
|
||||
'ExceptionHandling': 1,
|
||||
'DisableSpecificWarnings': [
|
||||
4100, 4611
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
'Release': {
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
'WarningLevel': 4,
|
||||
'ExceptionHandling': 1,
|
||||
'DisableSpecificWarnings': [
|
||||
4100, 4611
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, { # 'OS!="win"'
|
||||
'libraries': [
|
||||
'<!@(pkg-config pixman-1 --libs)',
|
||||
'<!@(pkg-config cairo --libs)',
|
||||
'<!@(pkg-config libpng --libs)',
|
||||
'<!@(pkg-config pangocairo --libs)',
|
||||
'<!@(pkg-config freetype2 --libs)'
|
||||
],
|
||||
'include_dirs': [
|
||||
'<!@(pkg-config cairo --cflags-only-I | sed s/-I//g)',
|
||||
'<!@(pkg-config libpng --cflags-only-I | sed s/-I//g)',
|
||||
'<!@(pkg-config pangocairo --cflags-only-I | sed s/-I//g)',
|
||||
'<!@(pkg-config freetype2 --cflags-only-I | sed s/-I//g)'
|
||||
],
|
||||
'cflags': ['-Wno-cast-function-type'],
|
||||
'cflags!': ['-fno-exceptions'],
|
||||
'cflags_cc!': ['-fno-exceptions']
|
||||
}],
|
||||
['OS=="mac"', {
|
||||
'xcode_settings': {
|
||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
|
||||
}
|
||||
}],
|
||||
['with_jpeg=="true"', {
|
||||
'defines': [
|
||||
'HAVE_JPEG'
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'copies': [{
|
||||
'destination': '<(PRODUCT_DIR)',
|
||||
'files': [
|
||||
'<(jpeg_root)/bin/jpeg62.dll',
|
||||
]
|
||||
}],
|
||||
'include_dirs': [
|
||||
'<(jpeg_root)/include'
|
||||
],
|
||||
'libraries': [
|
||||
'-l<(jpeg_root)/lib/jpeg.lib',
|
||||
]
|
||||
}, {
|
||||
'libraries': [
|
||||
'-ljpeg'
|
||||
]
|
||||
}]
|
||||
]
|
||||
}],
|
||||
['with_gif=="true"', {
|
||||
'defines': [
|
||||
'HAVE_GIF'
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'libraries': [
|
||||
'-l<(GTK_Root)/lib/gif.lib'
|
||||
]
|
||||
}, {
|
||||
'libraries': [
|
||||
'-lgif'
|
||||
]
|
||||
}]
|
||||
]
|
||||
}],
|
||||
['with_rsvg=="true"', {
|
||||
'defines': [
|
||||
'HAVE_RSVG'
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'copies': [{
|
||||
'destination': '<(PRODUCT_DIR)',
|
||||
'files': [
|
||||
'<(GTK_Root)/bin/librsvg-2-2.dll',
|
||||
'<(GTK_Root)/bin/libgdk_pixbuf-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libgio-2.0-0.dll',
|
||||
'<(GTK_Root)/bin/libcroco-0.6-3.dll',
|
||||
'<(GTK_Root)/bin/libgsf-1-114.dll',
|
||||
'<(GTK_Root)/bin/libxml2-2.dll'
|
||||
]
|
||||
}],
|
||||
'libraries': [
|
||||
'-l<(GTK_Root)/lib/librsvg-2-2.lib'
|
||||
]
|
||||
}, {
|
||||
'include_dirs': [
|
||||
'<!@(pkg-config librsvg-2.0 --cflags-only-I | sed s/-I//g)'
|
||||
],
|
||||
'libraries': [
|
||||
'<!@(pkg-config librsvg-2.0 --libs)'
|
||||
]
|
||||
}]
|
||||
]
|
||||
}]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
35
node_modules/canvas/browser.js
generated
vendored
Normal file
35
node_modules/canvas/browser.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
/* globals document, ImageData */
|
||||
|
||||
const parseFont = require('./lib/parse-font')
|
||||
|
||||
exports.parseFont = parseFont
|
||||
|
||||
exports.createCanvas = function (width, height) {
|
||||
return Object.assign(document.createElement('canvas'), { width: width, height: height })
|
||||
}
|
||||
|
||||
exports.createImageData = function (array, width, height) {
|
||||
// Browser implementation of ImageData looks at the number of arguments passed
|
||||
switch (arguments.length) {
|
||||
case 0: return new ImageData()
|
||||
case 1: return new ImageData(array)
|
||||
case 2: return new ImageData(array, width)
|
||||
default: return new ImageData(array, width, height)
|
||||
}
|
||||
}
|
||||
|
||||
exports.loadImage = function (src, options) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const image = Object.assign(document.createElement('img'), options)
|
||||
|
||||
function cleanup () {
|
||||
image.onload = null
|
||||
image.onerror = null
|
||||
}
|
||||
|
||||
image.onload = function () { cleanup(); resolve(image) }
|
||||
image.onerror = function () { cleanup(); reject(new Error('Failed to load the image "' + src + '"')) }
|
||||
|
||||
image.src = src
|
||||
})
|
||||
}
|
||||
BIN
node_modules/canvas/build/Release/canvas.exp
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/canvas.exp
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/canvas.ilk
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/canvas.ilk
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/canvas.lib
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/canvas.lib
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/canvas.node
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/canvas.node
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/canvas.pdb
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/canvas.pdb
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libbrotlicommon.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libbrotlicommon.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libbrotlidec.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libbrotlidec.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libbz2-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libbz2-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libcairo-2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libcairo-2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libcairo-gobject-2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libcairo-gobject-2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libdatrie-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libdatrie-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libexpat-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libexpat-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libffi-7.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libffi-7.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libfontconfig-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libfontconfig-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libfreetype-6.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libfreetype-6.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libfribidi-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libfribidi-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgcc_s_seh-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgcc_s_seh-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgdk_pixbuf-2.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgdk_pixbuf-2.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgif-7.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgif-7.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgio-2.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgio-2.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libglib-2.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libglib-2.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgmodule-2.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgmodule-2.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgobject-2.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgobject-2.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libgraphite2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libgraphite2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libharfbuzz-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libharfbuzz-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libiconv-2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libiconv-2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libintl-8.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libintl-8.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libjpeg-8.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libjpeg-8.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/liblzma-5.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/liblzma-5.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpango-1.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpango-1.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpangocairo-1.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpangocairo-1.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpangoft2-1.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpangoft2-1.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpangowin32-1.0-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpangowin32-1.0-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpcre-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpcre-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpixman-1-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpixman-1-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libpng16-16.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libpng16-16.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/librsvg-2-2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/librsvg-2-2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libstdc++-6.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libstdc++-6.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libthai-0.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libthai-0.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libwinpthread-1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libwinpthread-1.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/libxml2-2.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/libxml2-2.dll
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/BMPParser.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/BMPParser.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/Backend.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/Backend.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/Backends.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/Backends.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/Canvas.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/Canvas.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasGradient.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasGradient.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasPattern.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasPattern.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasRenderingContext2d.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/CanvasRenderingContext2d.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/Image.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/Image.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/ImageBackend.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/ImageBackend.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/ImageData.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/ImageData.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/PdfBackend.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/PdfBackend.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/SvgBackend.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/SvgBackend.obj
generated
vendored
Normal file
Binary file not shown.
11
node_modules/canvas/build/Release/obj/canvas/canvas.node.recipe
generated
vendored
Normal file
11
node_modules/canvas/build/Release/obj/canvas/canvas.node.recipe
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<ProjectOutputs>
|
||||
<ProjectOutput>
|
||||
<FullPath>D:\a\node-canvas\node-canvas\build\Release\canvas.node</FullPath>
|
||||
</ProjectOutput>
|
||||
</ProjectOutputs>
|
||||
<ContentFiles />
|
||||
<SatelliteDlls />
|
||||
<NonRecipeFileRefs />
|
||||
</Project>
|
||||
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.4448.write.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.4448.write.1.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.command.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.command.1.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.read.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/CL.read.1.tlog
generated
vendored
Normal file
Binary file not shown.
2
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/canvas.lastbuildstate
generated
vendored
Normal file
2
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/canvas.lastbuildstate
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
PlatformToolSet=v142:VCToolArchitecture=Native64Bit:VCToolsVersion=14.28.29910:TargetPlatformVersion=10.0.19041.0:
|
||||
Release|x64|D:\a\node-canvas\node-canvas\build\|
|
||||
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/canvas.write.1u.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/canvas.write.1u.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.command.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.command.1.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.read.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.read.1.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.write.1.tlog
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/canvas.tlog/link.write.1.tlog
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/closure.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/closure.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/color.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/color.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/init.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/init.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/register_font.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/register_font.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/obj/canvas/win_delay_load_hook.obj
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/obj/canvas/win_delay_load_hook.obj
generated
vendored
Normal file
Binary file not shown.
BIN
node_modules/canvas/build/Release/zlib1.dll
generated
vendored
Normal file
BIN
node_modules/canvas/build/Release/zlib1.dll
generated
vendored
Normal file
Binary file not shown.
86
node_modules/canvas/index.js
generated
vendored
Normal file
86
node_modules/canvas/index.js
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
const Canvas = require('./lib/canvas')
|
||||
const Image = require('./lib/image')
|
||||
const CanvasRenderingContext2D = require('./lib/context2d')
|
||||
const parseFont = require('./lib/parse-font')
|
||||
const packageJson = require('./package.json')
|
||||
const bindings = require('./lib/bindings')
|
||||
const fs = require('fs')
|
||||
const PNGStream = require('./lib/pngstream')
|
||||
const PDFStream = require('./lib/pdfstream')
|
||||
const JPEGStream = require('./lib/jpegstream')
|
||||
const DOMMatrix = require('./lib/DOMMatrix').DOMMatrix
|
||||
const DOMPoint = require('./lib/DOMMatrix').DOMPoint
|
||||
|
||||
function createCanvas (width, height, type) {
|
||||
return new Canvas(width, height, type)
|
||||
}
|
||||
|
||||
function createImageData (array, width, height) {
|
||||
return new bindings.ImageData(array, width, height)
|
||||
}
|
||||
|
||||
function loadImage (src) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const image = new Image()
|
||||
|
||||
function cleanup () {
|
||||
image.onload = null
|
||||
image.onerror = null
|
||||
}
|
||||
|
||||
image.onload = () => { cleanup(); resolve(image) }
|
||||
image.onerror = (err) => { cleanup(); reject(err) }
|
||||
|
||||
image.src = src
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve paths for registerFont. Must be called *before* creating a Canvas
|
||||
* instance.
|
||||
* @param src {string} Path to font file.
|
||||
* @param fontFace {{family: string, weight?: string, style?: string}} Object
|
||||
* specifying font information. `weight` and `style` default to `"normal"`.
|
||||
*/
|
||||
function registerFont (src, fontFace) {
|
||||
// TODO this doesn't need to be on Canvas; it should just be a static method
|
||||
// of `bindings`.
|
||||
return Canvas._registerFont(fs.realpathSync(src), fontFace)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Canvas,
|
||||
Context2d: CanvasRenderingContext2D, // Legacy/compat export
|
||||
CanvasRenderingContext2D,
|
||||
CanvasGradient: bindings.CanvasGradient,
|
||||
CanvasPattern: bindings.CanvasPattern,
|
||||
Image,
|
||||
ImageData: bindings.ImageData,
|
||||
PNGStream,
|
||||
PDFStream,
|
||||
JPEGStream,
|
||||
DOMMatrix,
|
||||
DOMPoint,
|
||||
|
||||
registerFont,
|
||||
parseFont,
|
||||
|
||||
createCanvas,
|
||||
createImageData,
|
||||
loadImage,
|
||||
|
||||
backends: bindings.Backends,
|
||||
|
||||
/** Library version. */
|
||||
version: packageJson.version,
|
||||
/** Cairo version. */
|
||||
cairoVersion: bindings.cairoVersion,
|
||||
/** jpeglib version. */
|
||||
jpegVersion: bindings.jpegVersion,
|
||||
/** gif_lib version. */
|
||||
gifVersion: bindings.gifVersion ? bindings.gifVersion.replace(/[^.\d]/g, '') : undefined,
|
||||
/** freetype version. */
|
||||
freetypeVersion: bindings.freetypeVersion,
|
||||
/** rsvg version. */
|
||||
rsvgVersion: bindings.rsvgVersion
|
||||
}
|
||||
609
node_modules/canvas/lib/DOMMatrix.js
generated
vendored
Normal file
609
node_modules/canvas/lib/DOMMatrix.js
generated
vendored
Normal file
@@ -0,0 +1,609 @@
|
||||
'use strict'
|
||||
|
||||
const util = require('util')
|
||||
|
||||
// DOMMatrix per https://drafts.fxtf.org/geometry/#DOMMatrix
|
||||
|
||||
function DOMPoint(x, y, z, w) {
|
||||
if (!(this instanceof DOMPoint)) {
|
||||
throw new TypeError("Class constructors cannot be invoked without 'new'")
|
||||
}
|
||||
|
||||
if (typeof x === 'object') {
|
||||
w = x.w
|
||||
z = x.z
|
||||
y = x.y
|
||||
x = x.x
|
||||
}
|
||||
this.x = typeof x === 'number' ? x : 0
|
||||
this.y = typeof y === 'number' ? y : 0
|
||||
this.z = typeof z === 'number' ? z : 0
|
||||
this.w = typeof w === 'number' ? w : 1
|
||||
}
|
||||
|
||||
// Constants to index into _values (col-major)
|
||||
const M11 = 0, M12 = 1, M13 = 2, M14 = 3
|
||||
const M21 = 4, M22 = 5, M23 = 6, M24 = 7
|
||||
const M31 = 8, M32 = 9, M33 = 10, M34 = 11
|
||||
const M41 = 12, M42 = 13, M43 = 14, M44 = 15
|
||||
|
||||
const DEGREE_PER_RAD = 180 / Math.PI
|
||||
const RAD_PER_DEGREE = Math.PI / 180
|
||||
|
||||
function parseMatrix(init) {
|
||||
var parsed = init.replace(/matrix\(/, '')
|
||||
parsed = parsed.split(/,/, 7) // 6 + 1 to handle too many params
|
||||
if (parsed.length !== 6) throw new Error(`Failed to parse ${init}`)
|
||||
parsed = parsed.map(parseFloat)
|
||||
return [
|
||||
parsed[0], parsed[1], 0, 0,
|
||||
parsed[2], parsed[3], 0, 0,
|
||||
0, 0, 1, 0,
|
||||
parsed[4], parsed[5], 0, 1
|
||||
]
|
||||
}
|
||||
|
||||
function parseMatrix3d(init) {
|
||||
var parsed = init.replace(/matrix3d\(/, '')
|
||||
parsed = parsed.split(/,/, 17) // 16 + 1 to handle too many params
|
||||
if (parsed.length !== 16) throw new Error(`Failed to parse ${init}`)
|
||||
return parsed.map(parseFloat)
|
||||
}
|
||||
|
||||
function parseTransform(tform) {
|
||||
var type = tform.split(/\(/, 1)[0]
|
||||
switch (type) {
|
||||
case 'matrix':
|
||||
return parseMatrix(tform)
|
||||
case 'matrix3d':
|
||||
return parseMatrix3d(tform)
|
||||
// TODO This is supposed to support any CSS transform value.
|
||||
default:
|
||||
throw new Error(`${type} parsing not implemented`)
|
||||
}
|
||||
}
|
||||
|
||||
function DOMMatrix (init) {
|
||||
if (!(this instanceof DOMMatrix)) {
|
||||
throw new TypeError("Class constructors cannot be invoked without 'new'")
|
||||
}
|
||||
|
||||
this._is2D = true
|
||||
this._values = new Float64Array([
|
||||
1, 0, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
])
|
||||
|
||||
var i
|
||||
|
||||
if (typeof init === 'string') { // parse CSS transformList
|
||||
if (init === '') return // default identity matrix
|
||||
var tforms = init.split(/\)\s+/, 20).map(parseTransform)
|
||||
if (tforms.length === 0) return
|
||||
init = tforms[0]
|
||||
for (i = 1; i < tforms.length; i++) init = multiply(tforms[i], init)
|
||||
}
|
||||
|
||||
i = 0
|
||||
if (init && init.length === 6) {
|
||||
setNumber2D(this, M11, init[i++])
|
||||
setNumber2D(this, M12, init[i++])
|
||||
setNumber2D(this, M21, init[i++])
|
||||
setNumber2D(this, M22, init[i++])
|
||||
setNumber2D(this, M41, init[i++])
|
||||
setNumber2D(this, M42, init[i++])
|
||||
} else if (init && init.length === 16) {
|
||||
setNumber2D(this, M11, init[i++])
|
||||
setNumber2D(this, M12, init[i++])
|
||||
setNumber3D(this, M13, init[i++])
|
||||
setNumber3D(this, M14, init[i++])
|
||||
setNumber2D(this, M21, init[i++])
|
||||
setNumber2D(this, M22, init[i++])
|
||||
setNumber3D(this, M23, init[i++])
|
||||
setNumber3D(this, M24, init[i++])
|
||||
setNumber3D(this, M31, init[i++])
|
||||
setNumber3D(this, M32, init[i++])
|
||||
setNumber3D(this, M33, init[i++])
|
||||
setNumber3D(this, M34, init[i++])
|
||||
setNumber2D(this, M41, init[i++])
|
||||
setNumber2D(this, M42, init[i++])
|
||||
setNumber3D(this, M43, init[i++])
|
||||
setNumber3D(this, M44, init[i])
|
||||
} else if (init !== undefined) {
|
||||
throw new TypeError('Expected string or array.')
|
||||
}
|
||||
}
|
||||
|
||||
DOMMatrix.fromMatrix = function (init) {
|
||||
if (!(init instanceof DOMMatrix)) throw new TypeError('Expected DOMMatrix')
|
||||
return new DOMMatrix(init._values)
|
||||
}
|
||||
DOMMatrix.fromFloat32Array = function (init) {
|
||||
if (!(init instanceof Float32Array)) throw new TypeError('Expected Float32Array')
|
||||
return new DOMMatrix(init)
|
||||
}
|
||||
DOMMatrix.fromFloat64Array = function (init) {
|
||||
if (!(init instanceof Float64Array)) throw new TypeError('Expected Float64Array')
|
||||
return new DOMMatrix(init)
|
||||
}
|
||||
|
||||
// TODO || is for Node.js pre-v6.6.0
|
||||
DOMMatrix.prototype[util.inspect.custom || 'inspect'] = function (depth, options) {
|
||||
if (depth < 0) return '[DOMMatrix]'
|
||||
|
||||
return `DOMMatrix [
|
||||
a: ${this.a}
|
||||
b: ${this.b}
|
||||
c: ${this.c}
|
||||
d: ${this.d}
|
||||
e: ${this.e}
|
||||
f: ${this.f}
|
||||
m11: ${this.m11}
|
||||
m12: ${this.m12}
|
||||
m13: ${this.m13}
|
||||
m14: ${this.m14}
|
||||
m21: ${this.m21}
|
||||
m22: ${this.m22}
|
||||
m23: ${this.m23}
|
||||
m23: ${this.m23}
|
||||
m31: ${this.m31}
|
||||
m32: ${this.m32}
|
||||
m33: ${this.m33}
|
||||
m34: ${this.m34}
|
||||
m41: ${this.m41}
|
||||
m42: ${this.m42}
|
||||
m43: ${this.m43}
|
||||
m44: ${this.m44}
|
||||
is2D: ${this.is2D}
|
||||
isIdentity: ${this.isIdentity} ]`
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.toString = function () {
|
||||
return this.is2D ?
|
||||
`matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})` :
|
||||
`matrix3d(${this._values.join(', ')})`
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that `value` is a number and sets the value.
|
||||
*/
|
||||
function setNumber2D(receiver, index, value) {
|
||||
if (typeof value !== 'number') throw new TypeError('Expected number')
|
||||
return receiver._values[index] = value
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that `value` is a number, sets `_is2D = false` if necessary and sets
|
||||
* the value.
|
||||
*/
|
||||
function setNumber3D(receiver, index, value) {
|
||||
if (typeof value !== 'number') throw new TypeError('Expected number')
|
||||
if (index === M33 || index === M44) {
|
||||
if (value !== 1) receiver._is2D = false
|
||||
} else if (value !== 0) receiver._is2D = false
|
||||
return receiver._values[index] = value
|
||||
}
|
||||
|
||||
Object.defineProperties(DOMMatrix.prototype, {
|
||||
m11: {get: function () { return this._values[M11] }, set: function (v) { return setNumber2D(this, M11, v) }},
|
||||
m12: {get: function () { return this._values[M12] }, set: function (v) { return setNumber2D(this, M12, v) }},
|
||||
m13: {get: function () { return this._values[M13] }, set: function (v) { return setNumber3D(this, M13, v) }},
|
||||
m14: {get: function () { return this._values[M14] }, set: function (v) { return setNumber3D(this, M14, v) }},
|
||||
m21: {get: function () { return this._values[M21] }, set: function (v) { return setNumber2D(this, M21, v) }},
|
||||
m22: {get: function () { return this._values[M22] }, set: function (v) { return setNumber2D(this, M22, v) }},
|
||||
m23: {get: function () { return this._values[M23] }, set: function (v) { return setNumber3D(this, M23, v) }},
|
||||
m24: {get: function () { return this._values[M24] }, set: function (v) { return setNumber3D(this, M24, v) }},
|
||||
m31: {get: function () { return this._values[M31] }, set: function (v) { return setNumber3D(this, M31, v) }},
|
||||
m32: {get: function () { return this._values[M32] }, set: function (v) { return setNumber3D(this, M32, v) }},
|
||||
m33: {get: function () { return this._values[M33] }, set: function (v) { return setNumber3D(this, M33, v) }},
|
||||
m34: {get: function () { return this._values[M34] }, set: function (v) { return setNumber3D(this, M34, v) }},
|
||||
m41: {get: function () { return this._values[M41] }, set: function (v) { return setNumber2D(this, M41, v) }},
|
||||
m42: {get: function () { return this._values[M42] }, set: function (v) { return setNumber2D(this, M42, v) }},
|
||||
m43: {get: function () { return this._values[M43] }, set: function (v) { return setNumber3D(this, M43, v) }},
|
||||
m44: {get: function () { return this._values[M44] }, set: function (v) { return setNumber3D(this, M44, v) }},
|
||||
|
||||
a: {get: function () { return this.m11 }, set: function (v) { return this.m11 = v }},
|
||||
b: {get: function () { return this.m12 }, set: function (v) { return this.m12 = v }},
|
||||
c: {get: function () { return this.m21 }, set: function (v) { return this.m21 = v }},
|
||||
d: {get: function () { return this.m22 }, set: function (v) { return this.m22 = v }},
|
||||
e: {get: function () { return this.m41 }, set: function (v) { return this.m41 = v }},
|
||||
f: {get: function () { return this.m42 }, set: function (v) { return this.m42 = v }},
|
||||
|
||||
is2D: {get: function () { return this._is2D }}, // read-only
|
||||
|
||||
isIdentity: {
|
||||
get: function () {
|
||||
var values = this._values
|
||||
return values[M11] === 1 && values[M12] === 0 && values[M13] === 0 && values[M14] === 0 &&
|
||||
values[M21] === 0 && values[M22] === 1 && values[M23] === 0 && values[M24] === 0 &&
|
||||
values[M31] === 0 && values[M32] === 0 && values[M33] === 1 && values[M34] === 0 &&
|
||||
values[M41] === 0 && values[M42] === 0 && values[M43] === 0 && values[M44] === 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Instantiates a DOMMatrix, bypassing the constructor.
|
||||
* @param {Float64Array} values Value to assign to `_values`. This is assigned
|
||||
* without copying (okay because all usages are followed by a multiply).
|
||||
*/
|
||||
function newInstance(values) {
|
||||
var instance = Object.create(DOMMatrix.prototype)
|
||||
instance.constructor = DOMMatrix
|
||||
instance._is2D = true
|
||||
instance._values = values
|
||||
return instance
|
||||
}
|
||||
|
||||
function multiply(A, B) {
|
||||
var dest = new Float64Array(16)
|
||||
for (var i = 0; i < 4; i++) {
|
||||
for (var j = 0; j < 4; j++) {
|
||||
var sum = 0
|
||||
for (var k = 0; k < 4; k++) {
|
||||
sum += A[i * 4 + k] * B[k * 4 + j]
|
||||
}
|
||||
dest[i * 4 + j] = sum
|
||||
}
|
||||
}
|
||||
return dest
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.multiply = function (other) {
|
||||
return newInstance(this._values).multiplySelf(other)
|
||||
}
|
||||
DOMMatrix.prototype.multiplySelf = function (other) {
|
||||
this._values = multiply(other._values, this._values)
|
||||
if (!other.is2D) this._is2D = false
|
||||
return this
|
||||
}
|
||||
DOMMatrix.prototype.preMultiplySelf = function (other) {
|
||||
this._values = multiply(this._values, other._values)
|
||||
if (!other.is2D) this._is2D = false
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.translate = function (tx, ty, tz) {
|
||||
return newInstance(this._values).translateSelf(tx, ty, tz)
|
||||
}
|
||||
DOMMatrix.prototype.translateSelf = function (tx, ty, tz) {
|
||||
if (typeof tx !== 'number') tx = 0
|
||||
if (typeof ty !== 'number') ty = 0
|
||||
if (typeof tz !== 'number') tz = 0
|
||||
this._values = multiply([
|
||||
1, 0, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
tx, ty, tz, 1
|
||||
], this._values)
|
||||
if (tz !== 0) this._is2D = false
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.scale = function (scaleX, scaleY, scaleZ, originX, originY, originZ) {
|
||||
return newInstance(this._values).scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ)
|
||||
}
|
||||
DOMMatrix.prototype.scale3d = function (scale, originX, originY, originZ) {
|
||||
return newInstance(this._values).scale3dSelf(scale, originX, originY, originZ)
|
||||
}
|
||||
DOMMatrix.prototype.scale3dSelf = function (scale, originX, originY, originZ) {
|
||||
return this.scaleSelf(scale, scale, scale, originX, originY, originZ)
|
||||
}
|
||||
DOMMatrix.prototype.scaleSelf = function (scaleX, scaleY, scaleZ, originX, originY, originZ) {
|
||||
// Not redundant with translate's checks because we need to negate the values later.
|
||||
if (typeof originX !== 'number') originX = 0
|
||||
if (typeof originY !== 'number') originY = 0
|
||||
if (typeof originZ !== 'number') originZ = 0
|
||||
this.translateSelf(originX, originY, originZ)
|
||||
if (typeof scaleX !== 'number') scaleX = 1
|
||||
if (typeof scaleY !== 'number') scaleY = scaleX
|
||||
if (typeof scaleZ !== 'number') scaleZ = 1
|
||||
this._values = multiply([
|
||||
scaleX, 0, 0, 0,
|
||||
0, scaleY, 0, 0,
|
||||
0, 0, scaleZ, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
this.translateSelf(-originX, -originY, -originZ)
|
||||
if (scaleZ !== 1 || originZ !== 0) this._is2D = false
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.rotateFromVector = function (x, y) {
|
||||
return newInstance(this._values).rotateFromVectorSelf(x, y)
|
||||
}
|
||||
DOMMatrix.prototype.rotateFromVectorSelf = function (x, y) {
|
||||
if (typeof x !== 'number') x = 0
|
||||
if (typeof y !== 'number') y = 0
|
||||
var theta = (x === 0 && y === 0) ? 0 : Math.atan2(y, x) * DEGREE_PER_RAD
|
||||
return this.rotateSelf(theta)
|
||||
}
|
||||
DOMMatrix.prototype.rotate = function (rotX, rotY, rotZ) {
|
||||
return newInstance(this._values).rotateSelf(rotX, rotY, rotZ)
|
||||
}
|
||||
DOMMatrix.prototype.rotateSelf = function (rotX, rotY, rotZ) {
|
||||
if (rotY === undefined && rotZ === undefined) {
|
||||
rotZ = rotX
|
||||
rotX = rotY = 0
|
||||
}
|
||||
if (typeof rotY !== 'number') rotY = 0
|
||||
if (typeof rotZ !== 'number') rotZ = 0
|
||||
if (rotX !== 0 || rotY !== 0) this._is2D = false
|
||||
rotX *= RAD_PER_DEGREE
|
||||
rotY *= RAD_PER_DEGREE
|
||||
rotZ *= RAD_PER_DEGREE
|
||||
var c, s
|
||||
c = Math.cos(rotZ)
|
||||
s = Math.sin(rotZ)
|
||||
this._values = multiply([
|
||||
c, s, 0, 0,
|
||||
-s, c, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
c = Math.cos(rotY)
|
||||
s = Math.sin(rotY)
|
||||
this._values = multiply([
|
||||
c, 0, -s, 0,
|
||||
0, 1, 0, 0,
|
||||
s, 0, c, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
c = Math.cos(rotX)
|
||||
s = Math.sin(rotX)
|
||||
this._values = multiply([
|
||||
1, 0, 0, 0,
|
||||
0, c, s, 0,
|
||||
0, -s, c, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.rotateAxisAngle = function (x, y, z, angle) {
|
||||
return newInstance(this._values).rotateAxisAngleSelf(x, y, z, angle)
|
||||
}
|
||||
DOMMatrix.prototype.rotateAxisAngleSelf = function (x, y, z, angle) {
|
||||
if (typeof x !== 'number') x = 0
|
||||
if (typeof y !== 'number') y = 0
|
||||
if (typeof z !== 'number') z = 0
|
||||
// Normalize axis
|
||||
var length = Math.sqrt(x * x + y * y + z * z)
|
||||
if (length === 0) return this
|
||||
if (length !== 1) {
|
||||
x /= length
|
||||
y /= length
|
||||
z /= length
|
||||
}
|
||||
angle *= RAD_PER_DEGREE
|
||||
var c = Math.cos(angle)
|
||||
var s = Math.sin(angle)
|
||||
var t = 1 - c
|
||||
var tx = t * x
|
||||
var ty = t * y
|
||||
// NB: This is the generic transform. If the axis is a major axis, there are
|
||||
// faster transforms.
|
||||
this._values = multiply([
|
||||
tx * x + c, tx * y + s * z, tx * z - s * y, 0,
|
||||
tx * y - s * z, ty * y + c, ty * z + s * x, 0,
|
||||
tx * z + s * y, ty * z - s * x, t * z * z + c, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
if (x !== 0 || y !== 0) this._is2D = false
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.skewX = function (sx) {
|
||||
return newInstance(this._values).skewXSelf(sx)
|
||||
}
|
||||
DOMMatrix.prototype.skewXSelf = function (sx) {
|
||||
if (typeof sx !== 'number') return this
|
||||
var t = Math.tan(sx * RAD_PER_DEGREE)
|
||||
this._values = multiply([
|
||||
1, 0, 0, 0,
|
||||
t, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.skewY = function (sy) {
|
||||
return newInstance(this._values).skewYSelf(sy)
|
||||
}
|
||||
DOMMatrix.prototype.skewYSelf = function (sy) {
|
||||
if (typeof sy !== 'number') return this
|
||||
var t = Math.tan(sy * RAD_PER_DEGREE)
|
||||
this._values = multiply([
|
||||
1, t, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values)
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.flipX = function () {
|
||||
return newInstance(multiply([
|
||||
-1, 0, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values))
|
||||
}
|
||||
DOMMatrix.prototype.flipY = function () {
|
||||
return newInstance(multiply([
|
||||
1, 0, 0, 0,
|
||||
0, -1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
], this._values))
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.inverse = function () {
|
||||
return newInstance(this._values).invertSelf()
|
||||
}
|
||||
DOMMatrix.prototype.invertSelf = function () {
|
||||
var m = this._values;
|
||||
var inv = m.map(v => 0);
|
||||
|
||||
inv[0] = m[5] * m[10] * m[15] -
|
||||
m[5] * m[11] * m[14] -
|
||||
m[9] * m[6] * m[15] +
|
||||
m[9] * m[7] * m[14] +
|
||||
m[13] * m[6] * m[11] -
|
||||
m[13] * m[7] * m[10];
|
||||
|
||||
inv[4] = -m[4] * m[10] * m[15] +
|
||||
m[4] * m[11] * m[14] +
|
||||
m[8] * m[6] * m[15] -
|
||||
m[8] * m[7] * m[14] -
|
||||
m[12] * m[6] * m[11] +
|
||||
m[12] * m[7] * m[10];
|
||||
|
||||
inv[8] = m[4] * m[9] * m[15] -
|
||||
m[4] * m[11] * m[13] -
|
||||
m[8] * m[5] * m[15] +
|
||||
m[8] * m[7] * m[13] +
|
||||
m[12] * m[5] * m[11] -
|
||||
m[12] * m[7] * m[9];
|
||||
|
||||
inv[12] = -m[4] * m[9] * m[14] +
|
||||
m[4] * m[10] * m[13] +
|
||||
m[8] * m[5] * m[14] -
|
||||
m[8] * m[6] * m[13] -
|
||||
m[12] * m[5] * m[10] +
|
||||
m[12] * m[6] * m[9];
|
||||
|
||||
// If the determinant is zero, this matrix cannot be inverted, and all
|
||||
// values should be set to NaN, with the is2D flag set to false.
|
||||
|
||||
var det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
|
||||
|
||||
if (det === 0) {
|
||||
this._values = m.map(v => NaN);
|
||||
this._is2D = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
inv[1] = -m[1] * m[10] * m[15] +
|
||||
m[1] * m[11] * m[14] +
|
||||
m[9] * m[2] * m[15] -
|
||||
m[9] * m[3] * m[14] -
|
||||
m[13] * m[2] * m[11] +
|
||||
m[13] * m[3] * m[10];
|
||||
|
||||
inv[5] = m[0] * m[10] * m[15] -
|
||||
m[0] * m[11] * m[14] -
|
||||
m[8] * m[2] * m[15] +
|
||||
m[8] * m[3] * m[14] +
|
||||
m[12] * m[2] * m[11] -
|
||||
m[12] * m[3] * m[10];
|
||||
|
||||
inv[9] = -m[0] * m[9] * m[15] +
|
||||
m[0] * m[11] * m[13] +
|
||||
m[8] * m[1] * m[15] -
|
||||
m[8] * m[3] * m[13] -
|
||||
m[12] * m[1] * m[11] +
|
||||
m[12] * m[3] * m[9];
|
||||
|
||||
inv[13] = m[0] * m[9] * m[14] -
|
||||
m[0] * m[10] * m[13] -
|
||||
m[8] * m[1] * m[14] +
|
||||
m[8] * m[2] * m[13] +
|
||||
m[12] * m[1] * m[10] -
|
||||
m[12] * m[2] * m[9];
|
||||
|
||||
inv[2] = m[1] * m[6] * m[15] -
|
||||
m[1] * m[7] * m[14] -
|
||||
m[5] * m[2] * m[15] +
|
||||
m[5] * m[3] * m[14] +
|
||||
m[13] * m[2] * m[7] -
|
||||
m[13] * m[3] * m[6];
|
||||
|
||||
inv[6] = -m[0] * m[6] * m[15] +
|
||||
m[0] * m[7] * m[14] +
|
||||
m[4] * m[2] * m[15] -
|
||||
m[4] * m[3] * m[14] -
|
||||
m[12] * m[2] * m[7] +
|
||||
m[12] * m[3] * m[6];
|
||||
|
||||
inv[10] = m[0] * m[5] * m[15] -
|
||||
m[0] * m[7] * m[13] -
|
||||
m[4] * m[1] * m[15] +
|
||||
m[4] * m[3] * m[13] +
|
||||
m[12] * m[1] * m[7] -
|
||||
m[12] * m[3] * m[5];
|
||||
|
||||
inv[14] = -m[0] * m[5] * m[14] +
|
||||
m[0] * m[6] * m[13] +
|
||||
m[4] * m[1] * m[14] -
|
||||
m[4] * m[2] * m[13] -
|
||||
m[12] * m[1] * m[6] +
|
||||
m[12] * m[2] * m[5];
|
||||
|
||||
inv[3] = -m[1] * m[6] * m[11] +
|
||||
m[1] * m[7] * m[10] +
|
||||
m[5] * m[2] * m[11] -
|
||||
m[5] * m[3] * m[10] -
|
||||
m[9] * m[2] * m[7] +
|
||||
m[9] * m[3] * m[6];
|
||||
|
||||
inv[7] = m[0] * m[6] * m[11] -
|
||||
m[0] * m[7] * m[10] -
|
||||
m[4] * m[2] * m[11] +
|
||||
m[4] * m[3] * m[10] +
|
||||
m[8] * m[2] * m[7] -
|
||||
m[8] * m[3] * m[6];
|
||||
|
||||
inv[11] = -m[0] * m[5] * m[11] +
|
||||
m[0] * m[7] * m[9] +
|
||||
m[4] * m[1] * m[11] -
|
||||
m[4] * m[3] * m[9] -
|
||||
m[8] * m[1] * m[7] +
|
||||
m[8] * m[3] * m[5];
|
||||
|
||||
inv[15] = m[0] * m[5] * m[10] -
|
||||
m[0] * m[6] * m[9] -
|
||||
m[4] * m[1] * m[10] +
|
||||
m[4] * m[2] * m[9] +
|
||||
m[8] * m[1] * m[6] -
|
||||
m[8] * m[2] * m[5];
|
||||
|
||||
inv.forEach((v,i) => inv[i] = v/det);
|
||||
this._values = inv;
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.setMatrixValue = function (transformList) {
|
||||
var temp = new DOMMatrix(transformList)
|
||||
this._values = temp._values
|
||||
this._is2D = temp._is2D
|
||||
return this
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.transformPoint = function (point) {
|
||||
point = new DOMPoint(point)
|
||||
var x = point.x
|
||||
var y = point.y
|
||||
var z = point.z
|
||||
var w = point.w
|
||||
var values = this._values
|
||||
var nx = values[M11] * x + values[M21] * y + values[M31] * z + values[M41] * w
|
||||
var ny = values[M12] * x + values[M22] * y + values[M32] * z + values[M42] * w
|
||||
var nz = values[M13] * x + values[M23] * y + values[M33] * z + values[M43] * w
|
||||
var nw = values[M14] * x + values[M24] * y + values[M34] * z + values[M44] * w
|
||||
return new DOMPoint(nx, ny, nz, nw)
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.toFloat32Array = function () {
|
||||
return Float32Array.from(this._values)
|
||||
}
|
||||
|
||||
DOMMatrix.prototype.toFloat64Array = function () {
|
||||
return this._values.slice(0)
|
||||
}
|
||||
|
||||
module.exports = {DOMMatrix, DOMPoint}
|
||||
3
node_modules/canvas/lib/bindings.js
generated
vendored
Normal file
3
node_modules/canvas/lib/bindings.js
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = require('../build/Release/canvas.node');
|
||||
113
node_modules/canvas/lib/canvas.js
generated
vendored
Normal file
113
node_modules/canvas/lib/canvas.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Canvas
|
||||
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
const bindings = require('./bindings')
|
||||
const Canvas = module.exports = bindings.Canvas
|
||||
const Context2d = require('./context2d')
|
||||
const PNGStream = require('./pngstream')
|
||||
const PDFStream = require('./pdfstream')
|
||||
const JPEGStream = require('./jpegstream')
|
||||
const FORMATS = ['image/png', 'image/jpeg']
|
||||
const util = require('util')
|
||||
|
||||
// TODO || is for Node.js pre-v6.6.0
|
||||
Canvas.prototype[util.inspect.custom || 'inspect'] = function () {
|
||||
return `[Canvas ${this.width}x${this.height}]`
|
||||
}
|
||||
|
||||
Canvas.prototype.getContext = function (contextType, contextAttributes) {
|
||||
if ('2d' == contextType) {
|
||||
var ctx = this._context2d || (this._context2d = new Context2d(this, contextAttributes));
|
||||
this.context = ctx;
|
||||
ctx.canvas = this;
|
||||
return ctx;
|
||||
}
|
||||
};
|
||||
|
||||
Canvas.prototype.pngStream =
|
||||
Canvas.prototype.createPNGStream = function(options){
|
||||
return new PNGStream(this, options);
|
||||
};
|
||||
|
||||
Canvas.prototype.pdfStream =
|
||||
Canvas.prototype.createPDFStream = function(options){
|
||||
return new PDFStream(this, options);
|
||||
};
|
||||
|
||||
Canvas.prototype.jpegStream =
|
||||
Canvas.prototype.createJPEGStream = function(options){
|
||||
return new JPEGStream(this, options);
|
||||
};
|
||||
|
||||
Canvas.prototype.toDataURL = function(a1, a2, a3){
|
||||
// valid arg patterns (args -> [type, opts, fn]):
|
||||
// [] -> ['image/png', null, null]
|
||||
// [qual] -> ['image/png', null, null]
|
||||
// [undefined] -> ['image/png', null, null]
|
||||
// ['image/png'] -> ['image/png', null, null]
|
||||
// ['image/png', qual] -> ['image/png', null, null]
|
||||
// [fn] -> ['image/png', null, fn]
|
||||
// [type, fn] -> [type, null, fn]
|
||||
// [undefined, fn] -> ['image/png', null, fn]
|
||||
// ['image/png', qual, fn] -> ['image/png', null, fn]
|
||||
// ['image/jpeg', fn] -> ['image/jpeg', null, fn]
|
||||
// ['image/jpeg', opts, fn] -> ['image/jpeg', opts, fn]
|
||||
// ['image/jpeg', qual, fn] -> ['image/jpeg', {quality: qual}, fn]
|
||||
// ['image/jpeg', undefined, fn] -> ['image/jpeg', null, fn]
|
||||
// ['image/jpeg'] -> ['image/jpeg', null, fn]
|
||||
// ['image/jpeg', opts] -> ['image/jpeg', opts, fn]
|
||||
// ['image/jpeg', qual] -> ['image/jpeg', {quality: qual}, fn]
|
||||
|
||||
var type = 'image/png';
|
||||
var opts = {};
|
||||
var fn;
|
||||
|
||||
if ('function' === typeof a1) {
|
||||
fn = a1;
|
||||
} else {
|
||||
if ('string' === typeof a1 && FORMATS.includes(a1.toLowerCase())) {
|
||||
type = a1.toLowerCase();
|
||||
}
|
||||
|
||||
if ('function' === typeof a2) {
|
||||
fn = a2;
|
||||
} else {
|
||||
if ('object' === typeof a2) {
|
||||
opts = a2;
|
||||
} else if ('number' === typeof a2) {
|
||||
opts = {quality: Math.max(0, Math.min(1, a2))};
|
||||
}
|
||||
|
||||
if ('function' === typeof a3) {
|
||||
fn = a3;
|
||||
} else if (undefined !== a3) {
|
||||
throw new TypeError(typeof a3 + ' is not a function');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.width === 0 || this.height === 0) {
|
||||
// Per spec, if the bitmap has no pixels, return this string:
|
||||
var str = "data:,";
|
||||
if (fn) {
|
||||
setTimeout(() => fn(null, str));
|
||||
return;
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
if (fn) {
|
||||
this.toBuffer((err, buf) => {
|
||||
if (err) return fn(err);
|
||||
fn(null, `data:${type};base64,${buf.toString('base64')}`);
|
||||
}, type, opts)
|
||||
} else {
|
||||
return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
|
||||
}
|
||||
};
|
||||
14
node_modules/canvas/lib/context2d.js
generated
vendored
Normal file
14
node_modules/canvas/lib/context2d.js
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
/*!
|
||||
* Canvas - Context2d
|
||||
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
const bindings = require('./bindings')
|
||||
const parseFont = require('./parse-font')
|
||||
const { DOMMatrix } = require('./DOMMatrix')
|
||||
|
||||
bindings.CanvasRenderingContext2dInit(DOMMatrix, parseFont)
|
||||
module.exports = bindings.CanvasRenderingContext2d
|
||||
93
node_modules/canvas/lib/image.js
generated
vendored
Normal file
93
node_modules/canvas/lib/image.js
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Canvas - Image
|
||||
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const bindings = require('./bindings')
|
||||
const Image = module.exports = bindings.Image
|
||||
const util = require('util')
|
||||
|
||||
// Lazily loaded simple-get
|
||||
let get;
|
||||
|
||||
const {GetSource, SetSource} = bindings;
|
||||
|
||||
Object.defineProperty(Image.prototype, 'src', {
|
||||
/**
|
||||
* src setter. Valid values:
|
||||
* * `data:` URI
|
||||
* * Local file path
|
||||
* * HTTP or HTTPS URL
|
||||
* * Buffer containing image data (i.e. not a `data:` URI stored in a Buffer)
|
||||
*
|
||||
* @param {String|Buffer} val filename, buffer, data URI, URL
|
||||
* @api public
|
||||
*/
|
||||
set(val) {
|
||||
if (typeof val === 'string') {
|
||||
if (/^\s*data:/.test(val)) { // data: URI
|
||||
const commaI = val.indexOf(',')
|
||||
// 'base64' must come before the comma
|
||||
const isBase64 = val.lastIndexOf('base64', commaI) !== -1
|
||||
const content = val.slice(commaI + 1)
|
||||
setSource(this, Buffer.from(content, isBase64 ? 'base64' : 'utf8'), val);
|
||||
} else if (/^\s*https?:\/\//.test(val)) { // remote URL
|
||||
const onerror = err => {
|
||||
if (typeof this.onerror === 'function') {
|
||||
this.onerror(err)
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
if (!get) get = require('simple-get');
|
||||
|
||||
get.concat(val, (err, res, data) => {
|
||||
if (err) return onerror(err)
|
||||
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
return onerror(new Error(`Server responded with ${res.statusCode}`))
|
||||
}
|
||||
|
||||
setSource(this, data)
|
||||
})
|
||||
} else { // local file path assumed
|
||||
setSource(this, val);
|
||||
}
|
||||
} else if (Buffer.isBuffer(val)) {
|
||||
setSource(this, val);
|
||||
}
|
||||
},
|
||||
|
||||
get() {
|
||||
// TODO https://github.com/Automattic/node-canvas/issues/118
|
||||
return getSource(this);
|
||||
},
|
||||
|
||||
configurable: true
|
||||
});
|
||||
|
||||
// TODO || is for Node.js pre-v6.6.0
|
||||
Image.prototype[util.inspect.custom || 'inspect'] = function(){
|
||||
return '[Image'
|
||||
+ (this.complete ? ':' + this.width + 'x' + this.height : '')
|
||||
+ (this.src ? ' ' + this.src : '')
|
||||
+ (this.complete ? ' complete' : '')
|
||||
+ ']';
|
||||
};
|
||||
|
||||
function getSource(img){
|
||||
return img._originalSource || GetSource.call(img);
|
||||
}
|
||||
|
||||
function setSource(img, src, origSrc){
|
||||
SetSource.call(img, src);
|
||||
img._originalSource = origSrc;
|
||||
}
|
||||
45
node_modules/canvas/lib/jpegstream.js
generated
vendored
Normal file
45
node_modules/canvas/lib/jpegstream.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Canvas - JPEGStream
|
||||
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
var Readable = require('stream').Readable;
|
||||
var util = require('util');
|
||||
|
||||
var JPEGStream = module.exports = function JPEGStream(canvas, options) {
|
||||
if (!(this instanceof JPEGStream)) {
|
||||
throw new TypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
if (canvas.streamJPEGSync === undefined) {
|
||||
throw new Error("node-canvas was built without JPEG support.");
|
||||
}
|
||||
|
||||
Readable.call(this);
|
||||
|
||||
this.options = options;
|
||||
this.canvas = canvas;
|
||||
};
|
||||
|
||||
util.inherits(JPEGStream, Readable);
|
||||
|
||||
function noop() {}
|
||||
|
||||
JPEGStream.prototype._read = function _read() {
|
||||
// For now we're not controlling the c++ code's data emission, so we only
|
||||
// call canvas.streamJPEGSync once and let it emit data at will.
|
||||
this._read = noop;
|
||||
var self = this;
|
||||
self.canvas.streamJPEGSync(this.options, function(err, chunk){
|
||||
if (err) {
|
||||
self.emit('error', err);
|
||||
} else if (chunk) {
|
||||
self.push(chunk);
|
||||
} else {
|
||||
self.push(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
102
node_modules/canvas/lib/parse-font.js
generated
vendored
Normal file
102
node_modules/canvas/lib/parse-font.js
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Font RegExp helpers.
|
||||
*/
|
||||
|
||||
const weights = 'bold|bolder|lighter|[1-9]00'
|
||||
, styles = 'italic|oblique'
|
||||
, variants = 'small-caps'
|
||||
, stretches = 'ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded'
|
||||
, units = 'px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q'
|
||||
, string = '\'([^\']+)\'|"([^"]+)"|[\\w\\s-]+'
|
||||
|
||||
// [ [ <‘font-style’> || <font-variant-css21> || <‘font-weight’> || <‘font-stretch’> ]?
|
||||
// <‘font-size’> [ / <‘line-height’> ]? <‘font-family’> ]
|
||||
// https://drafts.csswg.org/css-fonts-3/#font-prop
|
||||
const weightRe = new RegExp('(' + weights + ') +', 'i')
|
||||
const styleRe = new RegExp('(' + styles + ') +', 'i')
|
||||
const variantRe = new RegExp('(' + variants + ') +', 'i')
|
||||
const stretchRe = new RegExp('(' + stretches + ') +', 'i')
|
||||
const sizeFamilyRe = new RegExp(
|
||||
'([\\d\\.]+)(' + units + ') *'
|
||||
+ '((?:' + string + ')( *, *(?:' + string + '))*)')
|
||||
|
||||
/**
|
||||
* Cache font parsing.
|
||||
*/
|
||||
|
||||
const cache = {}
|
||||
|
||||
const defaultHeight = 16 // pt, common browser default
|
||||
|
||||
/**
|
||||
* Parse font `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {Object} Parsed font. `size` is in device units. `unit` is the unit
|
||||
* appearing in the input string.
|
||||
* @api private
|
||||
*/
|
||||
|
||||
module.exports = function (str) {
|
||||
// Cached
|
||||
if (cache[str]) return cache[str]
|
||||
|
||||
// Try for required properties first.
|
||||
const sizeFamily = sizeFamilyRe.exec(str)
|
||||
if (!sizeFamily) return // invalid
|
||||
|
||||
// Default values and required properties
|
||||
const font = {
|
||||
weight: 'normal',
|
||||
style: 'normal',
|
||||
stretch: 'normal',
|
||||
variant: 'normal',
|
||||
size: parseFloat(sizeFamily[1]),
|
||||
unit: sizeFamily[2],
|
||||
family: sizeFamily[3].replace(/["']/g, '').replace(/ *, */g, ',')
|
||||
}
|
||||
|
||||
// Optional, unordered properties.
|
||||
let weight, style, variant, stretch
|
||||
// Stop search at `sizeFamily.index`
|
||||
let substr = str.substring(0, sizeFamily.index)
|
||||
if ((weight = weightRe.exec(substr))) font.weight = weight[1]
|
||||
if ((style = styleRe.exec(substr))) font.style = style[1]
|
||||
if ((variant = variantRe.exec(substr))) font.variant = variant[1]
|
||||
if ((stretch = stretchRe.exec(substr))) font.stretch = stretch[1]
|
||||
|
||||
// Convert to device units. (`font.unit` is the original unit)
|
||||
// TODO: ch, ex
|
||||
switch (font.unit) {
|
||||
case 'pt':
|
||||
font.size /= 0.75
|
||||
break
|
||||
case 'pc':
|
||||
font.size *= 16
|
||||
break
|
||||
case 'in':
|
||||
font.size *= 96
|
||||
break
|
||||
case 'cm':
|
||||
font.size *= 96.0 / 2.54
|
||||
break
|
||||
case 'mm':
|
||||
font.size *= 96.0 / 25.4
|
||||
break
|
||||
case '%':
|
||||
// TODO disabled because existing unit tests assume 100
|
||||
// font.size *= defaultHeight / 100 / 0.75
|
||||
break
|
||||
case 'em':
|
||||
case 'rem':
|
||||
font.size *= defaultHeight / 0.75
|
||||
break
|
||||
case 'q':
|
||||
font.size *= 96 / 25.4 / 4
|
||||
break
|
||||
}
|
||||
|
||||
return (cache[str] = font)
|
||||
}
|
||||
39
node_modules/canvas/lib/pdfstream.js
generated
vendored
Normal file
39
node_modules/canvas/lib/pdfstream.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Canvas - PDFStream
|
||||
*/
|
||||
|
||||
var Readable = require('stream').Readable;
|
||||
var util = require('util');
|
||||
|
||||
var PDFStream = module.exports = function PDFStream(canvas, options) {
|
||||
if (!(this instanceof PDFStream)) {
|
||||
throw new TypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
Readable.call(this);
|
||||
|
||||
this.canvas = canvas;
|
||||
this.options = options;
|
||||
};
|
||||
|
||||
util.inherits(PDFStream, Readable);
|
||||
|
||||
function noop() {}
|
||||
|
||||
PDFStream.prototype._read = function _read() {
|
||||
// For now we're not controlling the c++ code's data emission, so we only
|
||||
// call canvas.streamPDFSync once and let it emit data at will.
|
||||
this._read = noop;
|
||||
var self = this;
|
||||
self.canvas.streamPDFSync(function(err, chunk, len){
|
||||
if (err) {
|
||||
self.emit('error', err);
|
||||
} else if (len) {
|
||||
self.push(chunk);
|
||||
} else {
|
||||
self.push(null);
|
||||
}
|
||||
}, this.options);
|
||||
};
|
||||
46
node_modules/canvas/lib/pngstream.js
generated
vendored
Normal file
46
node_modules/canvas/lib/pngstream.js
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Canvas - PNGStream
|
||||
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
var Readable = require('stream').Readable;
|
||||
var util = require('util');
|
||||
|
||||
var PNGStream = module.exports = function PNGStream(canvas, options) {
|
||||
if (!(this instanceof PNGStream)) {
|
||||
throw new TypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
Readable.call(this);
|
||||
|
||||
if (options &&
|
||||
options.palette instanceof Uint8ClampedArray &&
|
||||
options.palette.length % 4 !== 0) {
|
||||
throw new Error("Palette length must be a multiple of 4.");
|
||||
}
|
||||
this.canvas = canvas;
|
||||
this.options = options || {};
|
||||
};
|
||||
|
||||
util.inherits(PNGStream, Readable);
|
||||
|
||||
function noop() {}
|
||||
|
||||
PNGStream.prototype._read = function _read() {
|
||||
// For now we're not controlling the c++ code's data emission, so we only
|
||||
// call canvas.streamPNGSync once and let it emit data at will.
|
||||
this._read = noop;
|
||||
var self = this;
|
||||
self.canvas.streamPNGSync(function(err, chunk, len){
|
||||
if (err) {
|
||||
self.emit('error', err);
|
||||
} else if (len) {
|
||||
self.push(chunk);
|
||||
} else {
|
||||
self.push(null);
|
||||
}
|
||||
}, self.options);
|
||||
};
|
||||
113
node_modules/canvas/package.json
generated
vendored
Normal file
113
node_modules/canvas/package.json
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"_from": "canvas",
|
||||
"_id": "canvas@2.8.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-gLTi17X8WY9Cf5GZ2Yns8T5lfBOcGgFehDFb+JQwDqdOoBOcECS9ZWMEAqMSVcMYwXD659J8NyzjRY/2aE+C2Q==",
|
||||
"_location": "/canvas",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "canvas",
|
||||
"name": "canvas",
|
||||
"escapedName": "canvas",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/canvas/-/canvas-2.8.0.tgz",
|
||||
"_shasum": "f99ca7f25e6e26686661ffa4fec1239bbef74461",
|
||||
"_spec": "canvas",
|
||||
"_where": "C:\\Users\\dredgy\\RiderProjects\\DredgePos\\DredgePos",
|
||||
"author": {
|
||||
"name": "TJ Holowaychuk",
|
||||
"email": "tj@learnboost.com"
|
||||
},
|
||||
"binary": {
|
||||
"module_name": "canvas",
|
||||
"module_path": "build/Release",
|
||||
"host": "https://github.com/Automattic/node-canvas/releases/download/",
|
||||
"remote_path": "v{version}",
|
||||
"package_name": "{module_name}-v{version}-{node_abi}-{platform}-{libc}-{arch}.tar.gz"
|
||||
},
|
||||
"browser": "browser.js",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Automattic/node-canvas/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Nathan Rajlich",
|
||||
"email": "nathan@tootallnate.net"
|
||||
},
|
||||
{
|
||||
"name": "Rod Vagg",
|
||||
"email": "r@va.gg"
|
||||
},
|
||||
{
|
||||
"name": "Juriy Zaytsev",
|
||||
"email": "kangax@gmail.com"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"@mapbox/node-pre-gyp": "^1.0.0",
|
||||
"nan": "^2.14.0",
|
||||
"simple-get": "^3.0.3"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Canvas graphics API backed by Cairo",
|
||||
"devDependencies": {
|
||||
"@types/node": "^10.12.18",
|
||||
"assert-rejects": "^1.0.0",
|
||||
"dtslint": "^4.0.7",
|
||||
"express": "^4.16.3",
|
||||
"mocha": "^5.2.0",
|
||||
"pixelmatch": "^4.0.2",
|
||||
"standard": "^12.0.1",
|
||||
"typescript": "^4.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"files": [
|
||||
"binding.gyp",
|
||||
"lib/",
|
||||
"src/",
|
||||
"util/",
|
||||
"types/index.d.ts"
|
||||
],
|
||||
"homepage": "https://github.com/Automattic/node-canvas",
|
||||
"keywords": [
|
||||
"canvas",
|
||||
"graphic",
|
||||
"graphics",
|
||||
"pixman",
|
||||
"cairo",
|
||||
"image",
|
||||
"images",
|
||||
"pdf"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "canvas",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/Automattic/node-canvas.git"
|
||||
},
|
||||
"scripts": {
|
||||
"benchmark": "node benchmarks/run.js",
|
||||
"dtslint": "dtslint types",
|
||||
"install": "node-pre-gyp install --fallback-to-build",
|
||||
"lint": "standard examples/*.js test/server.js test/public/*.js benchmarks/run.js lib/context2d.js util/has_lib.js browser.js index.js",
|
||||
"prebenchmark": "node-gyp build",
|
||||
"pretest-server": "node-gyp build",
|
||||
"test": "mocha test/*.test.js",
|
||||
"test-server": "node test/server.js"
|
||||
},
|
||||
"types": "types/index.d.ts",
|
||||
"version": "2.8.0"
|
||||
}
|
||||
18
node_modules/canvas/src/Backends.cc
generated
vendored
Normal file
18
node_modules/canvas/src/Backends.cc
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
#include "Backends.h"
|
||||
|
||||
#include "backend/ImageBackend.h"
|
||||
#include "backend/PdfBackend.h"
|
||||
#include "backend/SvgBackend.h"
|
||||
|
||||
using namespace v8;
|
||||
|
||||
void Backends::Initialize(Local<Object> target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
Local<Object> obj = Nan::New<Object>();
|
||||
ImageBackend::Initialize(obj);
|
||||
PdfBackend::Initialize(obj);
|
||||
SvgBackend::Initialize(obj);
|
||||
|
||||
Nan::Set(target, Nan::New<String>("Backends").ToLocalChecked(), obj).Check();
|
||||
}
|
||||
10
node_modules/canvas/src/Backends.h
generated
vendored
Normal file
10
node_modules/canvas/src/Backends.h
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include "backend/Backend.h"
|
||||
#include <nan.h>
|
||||
#include <v8.h>
|
||||
|
||||
class Backends : public Nan::ObjectWrap {
|
||||
public:
|
||||
static void Initialize(v8::Local<v8::Object> target);
|
||||
};
|
||||
932
node_modules/canvas/src/Canvas.cc
generated
vendored
Normal file
932
node_modules/canvas/src/Canvas.cc
generated
vendored
Normal file
@@ -0,0 +1,932 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#include "Canvas.h"
|
||||
|
||||
#include <algorithm> // std::min
|
||||
#include <assert.h>
|
||||
#include <cairo-pdf.h>
|
||||
#include <cairo-svg.h>
|
||||
#include "CanvasRenderingContext2d.h"
|
||||
#include "closure.h"
|
||||
#include <cstring>
|
||||
#include <cctype>
|
||||
#include <ctime>
|
||||
#include <glib.h>
|
||||
#include "PNG.h"
|
||||
#include "register_font.h"
|
||||
#include <sstream>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include "Util.h"
|
||||
#include <vector>
|
||||
#include "node_buffer.h"
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
#include "JPEGStream.h"
|
||||
#endif
|
||||
|
||||
#include "backend/ImageBackend.h"
|
||||
#include "backend/PdfBackend.h"
|
||||
#include "backend/SvgBackend.h"
|
||||
|
||||
#define GENERIC_FACE_ERROR \
|
||||
"The second argument to registerFont is required, and should be an object " \
|
||||
"with at least a family (string) and optionally weight (string/number) " \
|
||||
"and style (string)."
|
||||
|
||||
using namespace v8;
|
||||
using namespace std;
|
||||
|
||||
Nan::Persistent<FunctionTemplate> Canvas::constructor;
|
||||
|
||||
std::vector<FontFace> font_face_list;
|
||||
|
||||
/*
|
||||
* Initialize Canvas.
|
||||
*/
|
||||
|
||||
void
|
||||
Canvas::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Constructor
|
||||
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Canvas::New);
|
||||
constructor.Reset(ctor);
|
||||
ctor->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
ctor->SetClassName(Nan::New("Canvas").ToLocalChecked());
|
||||
|
||||
// Prototype
|
||||
Local<ObjectTemplate> proto = ctor->PrototypeTemplate();
|
||||
Nan::SetPrototypeMethod(ctor, "toBuffer", ToBuffer);
|
||||
Nan::SetPrototypeMethod(ctor, "streamPNGSync", StreamPNGSync);
|
||||
Nan::SetPrototypeMethod(ctor, "streamPDFSync", StreamPDFSync);
|
||||
#ifdef HAVE_JPEG
|
||||
Nan::SetPrototypeMethod(ctor, "streamJPEGSync", StreamJPEGSync);
|
||||
#endif
|
||||
SetProtoAccessor(proto, Nan::New("type").ToLocalChecked(), GetType, NULL, ctor);
|
||||
SetProtoAccessor(proto, Nan::New("stride").ToLocalChecked(), GetStride, NULL, ctor);
|
||||
SetProtoAccessor(proto, Nan::New("width").ToLocalChecked(), GetWidth, SetWidth, ctor);
|
||||
SetProtoAccessor(proto, Nan::New("height").ToLocalChecked(), GetHeight, SetHeight, ctor);
|
||||
|
||||
Nan::SetTemplate(proto, "PNG_NO_FILTERS", Nan::New<Uint32>(PNG_NO_FILTERS));
|
||||
Nan::SetTemplate(proto, "PNG_FILTER_NONE", Nan::New<Uint32>(PNG_FILTER_NONE));
|
||||
Nan::SetTemplate(proto, "PNG_FILTER_SUB", Nan::New<Uint32>(PNG_FILTER_SUB));
|
||||
Nan::SetTemplate(proto, "PNG_FILTER_UP", Nan::New<Uint32>(PNG_FILTER_UP));
|
||||
Nan::SetTemplate(proto, "PNG_FILTER_AVG", Nan::New<Uint32>(PNG_FILTER_AVG));
|
||||
Nan::SetTemplate(proto, "PNG_FILTER_PAETH", Nan::New<Uint32>(PNG_FILTER_PAETH));
|
||||
Nan::SetTemplate(proto, "PNG_ALL_FILTERS", Nan::New<Uint32>(PNG_ALL_FILTERS));
|
||||
|
||||
// Class methods
|
||||
Nan::SetMethod(ctor, "_registerFont", RegisterFont);
|
||||
|
||||
Local<Context> ctx = Nan::GetCurrentContext();
|
||||
Nan::Set(target,
|
||||
Nan::New("Canvas").ToLocalChecked(),
|
||||
ctor->GetFunction(ctx).ToLocalChecked());
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize a Canvas with the given width and height.
|
||||
*/
|
||||
|
||||
NAN_METHOD(Canvas::New) {
|
||||
if (!info.IsConstructCall()) {
|
||||
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
Backend* backend = NULL;
|
||||
if (info[0]->IsNumber()) {
|
||||
int width = Nan::To<uint32_t>(info[0]).FromMaybe(0), height = 0;
|
||||
|
||||
if (info[1]->IsNumber()) height = Nan::To<uint32_t>(info[1]).FromMaybe(0);
|
||||
|
||||
if (info[2]->IsString()) {
|
||||
if (0 == strcmp("pdf", *Nan::Utf8String(info[2])))
|
||||
backend = new PdfBackend(width, height);
|
||||
else if (0 == strcmp("svg", *Nan::Utf8String(info[2])))
|
||||
backend = new SvgBackend(width, height);
|
||||
else
|
||||
backend = new ImageBackend(width, height);
|
||||
}
|
||||
else
|
||||
backend = new ImageBackend(width, height);
|
||||
}
|
||||
else if (info[0]->IsObject()) {
|
||||
if (Nan::New(ImageBackend::constructor)->HasInstance(info[0]) ||
|
||||
Nan::New(PdfBackend::constructor)->HasInstance(info[0]) ||
|
||||
Nan::New(SvgBackend::constructor)->HasInstance(info[0])) {
|
||||
backend = Nan::ObjectWrap::Unwrap<Backend>(Nan::To<Object>(info[0]).ToLocalChecked());
|
||||
}else{
|
||||
return Nan::ThrowTypeError("Invalid arguments");
|
||||
}
|
||||
}
|
||||
else {
|
||||
backend = new ImageBackend(0, 0);
|
||||
}
|
||||
|
||||
if (!backend->isSurfaceValid()) {
|
||||
delete backend;
|
||||
return Nan::ThrowError(backend->getError());
|
||||
}
|
||||
|
||||
Canvas* canvas = new Canvas(backend);
|
||||
canvas->Wrap(info.This());
|
||||
|
||||
backend->setCanvas(canvas);
|
||||
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
/*
|
||||
* Get type string.
|
||||
*/
|
||||
|
||||
NAN_GETTER(Canvas::GetType) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<String>(canvas->backend()->getName()).ToLocalChecked());
|
||||
}
|
||||
|
||||
/*
|
||||
* Get stride.
|
||||
*/
|
||||
NAN_GETTER(Canvas::GetStride) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<Number>(canvas->stride()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Get width.
|
||||
*/
|
||||
|
||||
NAN_GETTER(Canvas::GetWidth) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<Number>(canvas->getWidth()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Set width.
|
||||
*/
|
||||
|
||||
NAN_SETTER(Canvas::SetWidth) {
|
||||
if (value->IsNumber()) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
canvas->backend()->setWidth(Nan::To<uint32_t>(value).FromMaybe(0));
|
||||
canvas->resurface(info.This());
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Get height.
|
||||
*/
|
||||
|
||||
NAN_GETTER(Canvas::GetHeight) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<Number>(canvas->getHeight()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Set height.
|
||||
*/
|
||||
|
||||
NAN_SETTER(Canvas::SetHeight) {
|
||||
if (value->IsNumber()) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
canvas->backend()->setHeight(Nan::To<uint32_t>(value).FromMaybe(0));
|
||||
canvas->resurface(info.This());
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* EIO toBuffer callback.
|
||||
*/
|
||||
|
||||
void
|
||||
Canvas::ToPngBufferAsync(uv_work_t *req) {
|
||||
PngClosure* closure = static_cast<PngClosure*>(req->data);
|
||||
|
||||
closure->status = canvas_write_to_png_stream(
|
||||
closure->canvas->surface(),
|
||||
PngClosure::writeVec,
|
||||
closure);
|
||||
}
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
void
|
||||
Canvas::ToJpegBufferAsync(uv_work_t *req) {
|
||||
JpegClosure* closure = static_cast<JpegClosure*>(req->data);
|
||||
write_to_jpeg_buffer(closure->canvas->surface(), closure);
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* EIO after toBuffer callback.
|
||||
*/
|
||||
|
||||
void
|
||||
Canvas::ToBufferAsyncAfter(uv_work_t *req) {
|
||||
Nan::HandleScope scope;
|
||||
Nan::AsyncResource async("canvas:ToBufferAsyncAfter");
|
||||
Closure* closure = static_cast<Closure*>(req->data);
|
||||
delete req;
|
||||
|
||||
if (closure->status) {
|
||||
Local<Value> argv[1] = { Canvas::Error(closure->status) };
|
||||
closure->cb.Call(1, argv, &async);
|
||||
} else {
|
||||
Local<Object> buf = Nan::CopyBuffer((char*)&closure->vec[0], closure->vec.size()).ToLocalChecked();
|
||||
Local<Value> argv[2] = { Nan::Null(), buf };
|
||||
closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
|
||||
}
|
||||
|
||||
closure->canvas->Unref();
|
||||
delete closure;
|
||||
}
|
||||
|
||||
static void parsePNGArgs(Local<Value> arg, PngClosure& pngargs) {
|
||||
if (arg->IsObject()) {
|
||||
Local<Object> obj = Nan::To<Object>(arg).ToLocalChecked();
|
||||
|
||||
Local<Value> cLevel = Nan::Get(obj, Nan::New("compressionLevel").ToLocalChecked()).ToLocalChecked();
|
||||
if (cLevel->IsUint32()) {
|
||||
uint32_t val = Nan::To<uint32_t>(cLevel).FromMaybe(0);
|
||||
// See quote below from spec section 4.12.5.5.
|
||||
if (val <= 9) pngargs.compressionLevel = val;
|
||||
}
|
||||
|
||||
Local<Value> rez = Nan::Get(obj, Nan::New("resolution").ToLocalChecked()).ToLocalChecked();
|
||||
if (rez->IsUint32()) {
|
||||
uint32_t val = Nan::To<uint32_t>(rez).FromMaybe(0);
|
||||
if (val > 0) pngargs.resolution = val;
|
||||
}
|
||||
|
||||
Local<Value> filters = Nan::Get(obj, Nan::New("filters").ToLocalChecked()).ToLocalChecked();
|
||||
if (filters->IsUint32()) pngargs.filters = Nan::To<uint32_t>(filters).FromMaybe(0);
|
||||
|
||||
Local<Value> palette = Nan::Get(obj, Nan::New("palette").ToLocalChecked()).ToLocalChecked();
|
||||
if (palette->IsUint8ClampedArray()) {
|
||||
Local<Uint8ClampedArray> palette_ta = palette.As<Uint8ClampedArray>();
|
||||
pngargs.nPaletteColors = palette_ta->Length();
|
||||
if (pngargs.nPaletteColors % 4 != 0) {
|
||||
throw "Palette length must be a multiple of 4.";
|
||||
}
|
||||
pngargs.nPaletteColors /= 4;
|
||||
Nan::TypedArrayContents<uint8_t> _paletteColors(palette_ta);
|
||||
pngargs.palette = *_paletteColors;
|
||||
// Optional background color index:
|
||||
Local<Value> backgroundIndexVal = Nan::Get(obj, Nan::New("backgroundIndex").ToLocalChecked()).ToLocalChecked();
|
||||
if (backgroundIndexVal->IsUint32()) {
|
||||
pngargs.backgroundIndex = static_cast<uint8_t>(Nan::To<uint32_t>(backgroundIndexVal).FromMaybe(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
static void parseJPEGArgs(Local<Value> arg, JpegClosure& jpegargs) {
|
||||
// "If Type(quality) is not Number, or if quality is outside that range, the
|
||||
// user agent must use its default quality value, as if the quality argument
|
||||
// had not been given." - 4.12.5.5
|
||||
if (arg->IsObject()) {
|
||||
Local<Object> obj = Nan::To<Object>(arg).ToLocalChecked();
|
||||
|
||||
Local<Value> qual = Nan::Get(obj, Nan::New("quality").ToLocalChecked()).ToLocalChecked();
|
||||
if (qual->IsNumber()) {
|
||||
double quality = Nan::To<double>(qual).FromMaybe(0);
|
||||
if (quality >= 0.0 && quality <= 1.0) {
|
||||
jpegargs.quality = static_cast<uint32_t>(100.0 * quality);
|
||||
}
|
||||
}
|
||||
|
||||
Local<Value> chroma = Nan::Get(obj, Nan::New("chromaSubsampling").ToLocalChecked()).ToLocalChecked();
|
||||
if (chroma->IsBoolean()) {
|
||||
bool subsample = Nan::To<bool>(chroma).FromMaybe(0);
|
||||
jpegargs.chromaSubsampling = subsample ? 2 : 1;
|
||||
} else if (chroma->IsNumber()) {
|
||||
jpegargs.chromaSubsampling = Nan::To<uint32_t>(chroma).FromMaybe(0);
|
||||
}
|
||||
|
||||
Local<Value> progressive = Nan::Get(obj, Nan::New("progressive").ToLocalChecked()).ToLocalChecked();
|
||||
if (!progressive->IsUndefined()) {
|
||||
jpegargs.progressive = Nan::To<bool>(progressive).FromMaybe(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
|
||||
|
||||
static inline void setPdfMetaStr(cairo_surface_t* surf, Local<Object> opts,
|
||||
cairo_pdf_metadata_t t, const char* pName) {
|
||||
auto propName = Nan::New(pName).ToLocalChecked();
|
||||
auto propValue = Nan::Get(opts, propName).ToLocalChecked();
|
||||
if (propValue->IsString()) {
|
||||
// (copies char data)
|
||||
cairo_pdf_surface_set_metadata(surf, t, *Nan::Utf8String(propValue));
|
||||
}
|
||||
}
|
||||
|
||||
static inline void setPdfMetaDate(cairo_surface_t* surf, Local<Object> opts,
|
||||
cairo_pdf_metadata_t t, const char* pName) {
|
||||
auto propName = Nan::New(pName).ToLocalChecked();
|
||||
auto propValue = Nan::Get(opts, propName).ToLocalChecked();
|
||||
if (propValue->IsDate()) {
|
||||
auto date = static_cast<time_t>(propValue.As<v8::Date>()->ValueOf() / 1000); // ms -> s
|
||||
char buf[sizeof "2011-10-08T07:07:09Z"];
|
||||
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&date));
|
||||
cairo_pdf_surface_set_metadata(surf, t, buf);
|
||||
}
|
||||
}
|
||||
|
||||
static void setPdfMetadata(Canvas* canvas, Local<Object> opts) {
|
||||
cairo_surface_t* surf = canvas->surface();
|
||||
|
||||
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_TITLE, "title");
|
||||
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_AUTHOR, "author");
|
||||
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_SUBJECT, "subject");
|
||||
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_KEYWORDS, "keywords");
|
||||
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_CREATOR, "creator");
|
||||
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_CREATE_DATE, "creationDate");
|
||||
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_MOD_DATE, "modDate");
|
||||
}
|
||||
|
||||
#endif // CAIRO 16+
|
||||
|
||||
/*
|
||||
* Converts/encodes data to a Buffer. Async when a callback function is passed.
|
||||
|
||||
* PDF canvases:
|
||||
(any) => Buffer
|
||||
("application/pdf", config) => Buffer
|
||||
|
||||
* SVG canvases:
|
||||
(any) => Buffer
|
||||
|
||||
* ARGB data:
|
||||
("raw") => Buffer
|
||||
|
||||
* PNG-encoded
|
||||
() => Buffer
|
||||
(undefined|"image/png", {compressionLevel?: number, filter?: number}) => Buffer
|
||||
((err: null|Error, buffer) => any)
|
||||
((err: null|Error, buffer) => any, undefined|"image/png", {compressionLevel?: number, filter?: number})
|
||||
|
||||
* JPEG-encoded
|
||||
("image/jpeg") => Buffer
|
||||
("image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number}) => Buffer
|
||||
((err: null|Error, buffer) => any, "image/jpeg")
|
||||
((err: null|Error, buffer) => any, "image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number})
|
||||
*/
|
||||
|
||||
NAN_METHOD(Canvas::ToBuffer) {
|
||||
cairo_status_t status;
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
|
||||
// Vector canvases, sync only
|
||||
const std::string name = canvas->backend()->getName();
|
||||
if (name == "pdf" || name == "svg") {
|
||||
// mime type may be present, but it's not checked
|
||||
PdfSvgClosure* closure;
|
||||
if (name == "pdf") {
|
||||
closure = static_cast<PdfBackend*>(canvas->backend())->closure();
|
||||
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
|
||||
if (info[1]->IsObject()) { // toBuffer("application/pdf", config)
|
||||
setPdfMetadata(canvas, Nan::To<Object>(info[1]).ToLocalChecked());
|
||||
}
|
||||
#endif // CAIRO 16+
|
||||
} else {
|
||||
closure = static_cast<SvgBackend*>(canvas->backend())->closure();
|
||||
}
|
||||
|
||||
cairo_surface_finish(canvas->surface());
|
||||
Local<Object> buf = Nan::CopyBuffer((char*)&closure->vec[0], closure->vec.size()).ToLocalChecked();
|
||||
info.GetReturnValue().Set(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
// Raw ARGB data -- just a memcpy()
|
||||
if (info[0]->StrictEquals(Nan::New<String>("raw").ToLocalChecked())) {
|
||||
cairo_surface_t *surface = canvas->surface();
|
||||
cairo_surface_flush(surface);
|
||||
if (canvas->nBytes() > node::Buffer::kMaxLength) {
|
||||
Nan::ThrowError("Data exceeds maximum buffer length.");
|
||||
return;
|
||||
}
|
||||
const unsigned char *data = cairo_image_surface_get_data(surface);
|
||||
Isolate* iso = Nan::GetCurrentContext()->GetIsolate();
|
||||
Local<Object> buf = node::Buffer::Copy(iso, reinterpret_cast<const char*>(data), canvas->nBytes()).ToLocalChecked();
|
||||
info.GetReturnValue().Set(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
// Sync PNG, default
|
||||
if (info[0]->IsUndefined() || info[0]->StrictEquals(Nan::New<String>("image/png").ToLocalChecked())) {
|
||||
try {
|
||||
PngClosure closure(canvas);
|
||||
parsePNGArgs(info[1], closure);
|
||||
if (closure.nPaletteColors == 0xFFFFFFFF) {
|
||||
Nan::ThrowError("Palette length must be a multiple of 4.");
|
||||
return;
|
||||
}
|
||||
|
||||
Nan::TryCatch try_catch;
|
||||
status = canvas_write_to_png_stream(canvas->surface(), PngClosure::writeVec, &closure);
|
||||
|
||||
if (try_catch.HasCaught()) {
|
||||
try_catch.ReThrow();
|
||||
} else if (status) {
|
||||
throw status;
|
||||
} else {
|
||||
// TODO it's possible to avoid this copy
|
||||
Local<Object> buf = Nan::CopyBuffer((char *)&closure.vec[0], closure.vec.size()).ToLocalChecked();
|
||||
info.GetReturnValue().Set(buf);
|
||||
}
|
||||
} catch (cairo_status_t ex) {
|
||||
Nan::ThrowError(Canvas::Error(ex));
|
||||
} catch (const char* ex) {
|
||||
Nan::ThrowError(ex);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Async PNG
|
||||
if (info[0]->IsFunction() &&
|
||||
(info[1]->IsUndefined() || info[1]->StrictEquals(Nan::New<String>("image/png").ToLocalChecked()))) {
|
||||
|
||||
PngClosure* closure;
|
||||
try {
|
||||
closure = new PngClosure(canvas);
|
||||
parsePNGArgs(info[2], *closure);
|
||||
} catch (cairo_status_t ex) {
|
||||
Nan::ThrowError(Canvas::Error(ex));
|
||||
return;
|
||||
} catch (const char* ex) {
|
||||
Nan::ThrowError(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
canvas->Ref();
|
||||
closure->cb.Reset(info[0].As<Function>());
|
||||
|
||||
uv_work_t* req = new uv_work_t;
|
||||
req->data = closure;
|
||||
// Make sure the surface exists since we won't have an isolate context in the async block:
|
||||
canvas->surface();
|
||||
uv_queue_work(uv_default_loop(), req, ToPngBufferAsync, (uv_after_work_cb)ToBufferAsyncAfter);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
// Sync JPEG
|
||||
Local<Value> jpegStr = Nan::New<String>("image/jpeg").ToLocalChecked();
|
||||
if (info[0]->StrictEquals(jpegStr)) {
|
||||
try {
|
||||
JpegClosure closure(canvas);
|
||||
parseJPEGArgs(info[1], closure);
|
||||
|
||||
Nan::TryCatch try_catch;
|
||||
write_to_jpeg_buffer(canvas->surface(), &closure);
|
||||
|
||||
if (try_catch.HasCaught()) {
|
||||
try_catch.ReThrow();
|
||||
} else {
|
||||
// TODO it's possible to avoid this copy.
|
||||
Local<Object> buf = Nan::CopyBuffer((char *)&closure.vec[0], closure.vec.size()).ToLocalChecked();
|
||||
info.GetReturnValue().Set(buf);
|
||||
}
|
||||
} catch (cairo_status_t ex) {
|
||||
Nan::ThrowError(Canvas::Error(ex));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Async JPEG
|
||||
if (info[0]->IsFunction() && info[1]->StrictEquals(jpegStr)) {
|
||||
JpegClosure* closure = new JpegClosure(canvas);
|
||||
parseJPEGArgs(info[2], *closure);
|
||||
|
||||
canvas->Ref();
|
||||
closure->cb.Reset(info[0].As<Function>());
|
||||
|
||||
uv_work_t* req = new uv_work_t;
|
||||
req->data = closure;
|
||||
// Make sure the surface exists since we won't have an isolate context in the async block:
|
||||
canvas->surface();
|
||||
uv_queue_work(uv_default_loop(), req, ToJpegBufferAsync, (uv_after_work_cb)ToBufferAsyncAfter);
|
||||
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Canvas::StreamPNG callback.
|
||||
*/
|
||||
|
||||
static cairo_status_t
|
||||
streamPNG(void *c, const uint8_t *data, unsigned len) {
|
||||
Nan::HandleScope scope;
|
||||
Nan::AsyncResource async("canvas:StreamPNG");
|
||||
PngClosure* closure = (PngClosure*) c;
|
||||
Local<Object> buf = Nan::CopyBuffer((char *)data, len).ToLocalChecked();
|
||||
Local<Value> argv[3] = {
|
||||
Nan::Null()
|
||||
, buf
|
||||
, Nan::New<Number>(len) };
|
||||
closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
|
||||
return CAIRO_STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
/*
|
||||
* Stream PNG data synchronously. TODO async
|
||||
* StreamPngSync(this, options: {palette?: Uint8ClampedArray, backgroundIndex?: uint32, compressionLevel: uint32, filters: uint32})
|
||||
*/
|
||||
|
||||
NAN_METHOD(Canvas::StreamPNGSync) {
|
||||
if (!info[0]->IsFunction())
|
||||
return Nan::ThrowTypeError("callback function required");
|
||||
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
|
||||
PngClosure closure(canvas);
|
||||
parsePNGArgs(info[1], closure);
|
||||
|
||||
closure.cb.Reset(Local<Function>::Cast(info[0]));
|
||||
|
||||
Nan::TryCatch try_catch;
|
||||
|
||||
cairo_status_t status = canvas_write_to_png_stream(canvas->surface(), streamPNG, &closure);
|
||||
|
||||
if (try_catch.HasCaught()) {
|
||||
try_catch.ReThrow();
|
||||
return;
|
||||
} else if (status) {
|
||||
Local<Value> argv[1] = { Canvas::Error(status) };
|
||||
Nan::Call(closure.cb, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
|
||||
} else {
|
||||
Local<Value> argv[3] = {
|
||||
Nan::Null()
|
||||
, Nan::Null()
|
||||
, Nan::New<Uint32>(0) };
|
||||
Nan::Call(closure.cb, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
struct PdfStreamInfo {
|
||||
Local<Function> fn;
|
||||
uint32_t len;
|
||||
uint8_t* data;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* Canvas::StreamPDF FreeCallback
|
||||
*/
|
||||
|
||||
void stream_pdf_free(char *, void *) {}
|
||||
|
||||
/*
|
||||
* Canvas::StreamPDF callback.
|
||||
*/
|
||||
|
||||
static cairo_status_t
|
||||
streamPDF(void *c, const uint8_t *data, unsigned len) {
|
||||
Nan::HandleScope scope;
|
||||
Nan::AsyncResource async("canvas:StreamPDF");
|
||||
PdfStreamInfo* streaminfo = static_cast<PdfStreamInfo*>(c);
|
||||
// TODO this is technically wrong, we're returning a pointer to the data in a
|
||||
// vector in a class with automatic storage duration. If the canvas goes out
|
||||
// of scope while we're in the handler, a use-after-free could happen.
|
||||
Local<Object> buf = Nan::NewBuffer(const_cast<char *>(reinterpret_cast<const char *>(data)), len, stream_pdf_free, 0).ToLocalChecked();
|
||||
Local<Value> argv[3] = {
|
||||
Nan::Null()
|
||||
, buf
|
||||
, Nan::New<Number>(len) };
|
||||
async.runInAsyncScope(Nan::GetCurrentContext()->Global(), streaminfo->fn, sizeof argv / sizeof *argv, argv);
|
||||
return CAIRO_STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
cairo_status_t canvas_write_to_pdf_stream(cairo_surface_t *surface, cairo_write_func_t write_func, PdfStreamInfo* streaminfo) {
|
||||
size_t whole_chunks = streaminfo->len / PAGE_SIZE;
|
||||
size_t remainder = streaminfo->len - whole_chunks * PAGE_SIZE;
|
||||
|
||||
for (size_t i = 0; i < whole_chunks; ++i) {
|
||||
write_func(streaminfo, &streaminfo->data[i * PAGE_SIZE], PAGE_SIZE);
|
||||
}
|
||||
|
||||
if (remainder) {
|
||||
write_func(streaminfo, &streaminfo->data[whole_chunks * PAGE_SIZE], remainder);
|
||||
}
|
||||
|
||||
return CAIRO_STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
/*
|
||||
* Stream PDF data synchronously.
|
||||
*/
|
||||
|
||||
NAN_METHOD(Canvas::StreamPDFSync) {
|
||||
if (!info[0]->IsFunction())
|
||||
return Nan::ThrowTypeError("callback function required");
|
||||
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.Holder());
|
||||
|
||||
if (canvas->backend()->getName() != "pdf")
|
||||
return Nan::ThrowTypeError("wrong canvas type");
|
||||
|
||||
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
|
||||
if (info[1]->IsObject()) {
|
||||
setPdfMetadata(canvas, Nan::To<Object>(info[1]).ToLocalChecked());
|
||||
}
|
||||
#endif
|
||||
|
||||
cairo_surface_finish(canvas->surface());
|
||||
|
||||
PdfSvgClosure* closure = static_cast<PdfBackend*>(canvas->backend())->closure();
|
||||
Local<Function> fn = info[0].As<Function>();
|
||||
PdfStreamInfo streaminfo;
|
||||
streaminfo.fn = fn;
|
||||
streaminfo.data = &closure->vec[0];
|
||||
streaminfo.len = closure->vec.size();
|
||||
|
||||
Nan::TryCatch try_catch;
|
||||
|
||||
cairo_status_t status = canvas_write_to_pdf_stream(canvas->surface(), streamPDF, &streaminfo);
|
||||
|
||||
if (try_catch.HasCaught()) {
|
||||
try_catch.ReThrow();
|
||||
} else if (status) {
|
||||
Local<Value> error = Canvas::Error(status);
|
||||
Nan::Call(fn, Nan::GetCurrentContext()->Global(), 1, &error);
|
||||
} else {
|
||||
Local<Value> argv[3] = {
|
||||
Nan::Null()
|
||||
, Nan::Null()
|
||||
, Nan::New<Uint32>(0) };
|
||||
Nan::Call(fn, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Stream JPEG data synchronously.
|
||||
*/
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
static uint32_t getSafeBufSize(Canvas* canvas) {
|
||||
// Don't allow the buffer size to exceed the size of the canvas (#674)
|
||||
// TODO not sure if this is really correct, but it fixed #674
|
||||
return (std::min)(canvas->getWidth() * canvas->getHeight() * 4, static_cast<int>(PAGE_SIZE));
|
||||
}
|
||||
|
||||
NAN_METHOD(Canvas::StreamJPEGSync) {
|
||||
if (!info[1]->IsFunction())
|
||||
return Nan::ThrowTypeError("callback function required");
|
||||
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
|
||||
JpegClosure closure(canvas);
|
||||
parseJPEGArgs(info[0], closure);
|
||||
closure.cb.Reset(Local<Function>::Cast(info[1]));
|
||||
|
||||
Nan::TryCatch try_catch;
|
||||
uint32_t bufsize = getSafeBufSize(canvas);
|
||||
write_to_jpeg_stream(canvas->surface(), bufsize, &closure);
|
||||
|
||||
if (try_catch.HasCaught()) {
|
||||
try_catch.ReThrow();
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
char *
|
||||
str_value(Local<Value> val, const char *fallback, bool can_be_number) {
|
||||
if (val->IsString() || (can_be_number && val->IsNumber())) {
|
||||
return g_strdup(*Nan::Utf8String(val));
|
||||
} else if (fallback) {
|
||||
return g_strdup(fallback);
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
NAN_METHOD(Canvas::RegisterFont) {
|
||||
if (!info[0]->IsString()) {
|
||||
return Nan::ThrowError("Wrong argument type");
|
||||
} else if (!info[1]->IsObject()) {
|
||||
return Nan::ThrowError(GENERIC_FACE_ERROR);
|
||||
}
|
||||
|
||||
Nan::Utf8String filePath(info[0]);
|
||||
PangoFontDescription *sys_desc = get_pango_font_description((unsigned char *) *filePath);
|
||||
|
||||
if (!sys_desc) return Nan::ThrowError("Could not parse font file");
|
||||
|
||||
PangoFontDescription *user_desc = pango_font_description_new();
|
||||
|
||||
// now check the attrs, there are many ways to be wrong
|
||||
Local<Object> js_user_desc = Nan::To<Object>(info[1]).ToLocalChecked();
|
||||
Local<String> family_prop = Nan::New<String>("family").ToLocalChecked();
|
||||
Local<String> weight_prop = Nan::New<String>("weight").ToLocalChecked();
|
||||
Local<String> style_prop = Nan::New<String>("style").ToLocalChecked();
|
||||
|
||||
char *family = str_value(Nan::Get(js_user_desc, family_prop).ToLocalChecked(), NULL, false);
|
||||
char *weight = str_value(Nan::Get(js_user_desc, weight_prop).ToLocalChecked(), "normal", true);
|
||||
char *style = str_value(Nan::Get(js_user_desc, style_prop).ToLocalChecked(), "normal", false);
|
||||
|
||||
if (family && weight && style) {
|
||||
pango_font_description_set_weight(user_desc, Canvas::GetWeightFromCSSString(weight));
|
||||
pango_font_description_set_style(user_desc, Canvas::GetStyleFromCSSString(style));
|
||||
pango_font_description_set_family(user_desc, family);
|
||||
|
||||
auto found = std::find_if(font_face_list.begin(), font_face_list.end(), [&](FontFace& f) {
|
||||
return pango_font_description_equal(f.sys_desc, sys_desc);
|
||||
});
|
||||
|
||||
if (found != font_face_list.end()) {
|
||||
pango_font_description_free(found->user_desc);
|
||||
found->user_desc = user_desc;
|
||||
} else if (register_font((unsigned char *) *filePath)) {
|
||||
FontFace face;
|
||||
face.user_desc = user_desc;
|
||||
face.sys_desc = sys_desc;
|
||||
font_face_list.push_back(face);
|
||||
} else {
|
||||
pango_font_description_free(user_desc);
|
||||
Nan::ThrowError("Could not load font to the system's font host");
|
||||
}
|
||||
} else {
|
||||
pango_font_description_free(user_desc);
|
||||
Nan::ThrowError(GENERIC_FACE_ERROR);
|
||||
}
|
||||
|
||||
g_free(family);
|
||||
g_free(weight);
|
||||
g_free(style);
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize cairo surface.
|
||||
*/
|
||||
|
||||
Canvas::Canvas(Backend* backend) : ObjectWrap() {
|
||||
_backend = backend;
|
||||
}
|
||||
|
||||
/*
|
||||
* Destroy cairo surface.
|
||||
*/
|
||||
|
||||
Canvas::~Canvas() {
|
||||
if (_backend != NULL) {
|
||||
delete _backend;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Get a PangoStyle from a CSS string (like "italic")
|
||||
*/
|
||||
|
||||
PangoStyle
|
||||
Canvas::GetStyleFromCSSString(const char *style) {
|
||||
PangoStyle s = PANGO_STYLE_NORMAL;
|
||||
|
||||
if (strlen(style) > 0) {
|
||||
if (0 == strcmp("italic", style)) {
|
||||
s = PANGO_STYLE_ITALIC;
|
||||
} else if (0 == strcmp("oblique", style)) {
|
||||
s = PANGO_STYLE_OBLIQUE;
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get a PangoWeight from a CSS string ("bold", "100", etc)
|
||||
*/
|
||||
|
||||
PangoWeight
|
||||
Canvas::GetWeightFromCSSString(const char *weight) {
|
||||
PangoWeight w = PANGO_WEIGHT_NORMAL;
|
||||
|
||||
if (strlen(weight) > 0) {
|
||||
if (0 == strcmp("bold", weight)) {
|
||||
w = PANGO_WEIGHT_BOLD;
|
||||
} else if (0 == strcmp("100", weight)) {
|
||||
w = PANGO_WEIGHT_THIN;
|
||||
} else if (0 == strcmp("200", weight)) {
|
||||
w = PANGO_WEIGHT_ULTRALIGHT;
|
||||
} else if (0 == strcmp("300", weight)) {
|
||||
w = PANGO_WEIGHT_LIGHT;
|
||||
} else if (0 == strcmp("400", weight)) {
|
||||
w = PANGO_WEIGHT_NORMAL;
|
||||
} else if (0 == strcmp("500", weight)) {
|
||||
w = PANGO_WEIGHT_MEDIUM;
|
||||
} else if (0 == strcmp("600", weight)) {
|
||||
w = PANGO_WEIGHT_SEMIBOLD;
|
||||
} else if (0 == strcmp("700", weight)) {
|
||||
w = PANGO_WEIGHT_BOLD;
|
||||
} else if (0 == strcmp("800", weight)) {
|
||||
w = PANGO_WEIGHT_ULTRABOLD;
|
||||
} else if (0 == strcmp("900", weight)) {
|
||||
w = PANGO_WEIGHT_HEAVY;
|
||||
}
|
||||
}
|
||||
|
||||
return w;
|
||||
}
|
||||
|
||||
/*
|
||||
* Given a user description, return a description that will select the
|
||||
* font either from the system or @font-face
|
||||
*/
|
||||
|
||||
PangoFontDescription *
|
||||
Canvas::ResolveFontDescription(const PangoFontDescription *desc) {
|
||||
// One of the user-specified families could map to multiple SFNT family names
|
||||
// if someone registered two different fonts under the same family name.
|
||||
// https://drafts.csswg.org/css-fonts-3/#font-style-matching
|
||||
FontFace best;
|
||||
istringstream families(pango_font_description_get_family(desc));
|
||||
unordered_set<string> seen_families;
|
||||
string resolved_families;
|
||||
bool first = true;
|
||||
|
||||
for (string family; getline(families, family, ','); ) {
|
||||
string renamed_families;
|
||||
for (auto& ff : font_face_list) {
|
||||
string pangofamily = string(pango_font_description_get_family(ff.user_desc));
|
||||
if (streq_casein(family, pangofamily)) {
|
||||
const char* sys_desc_family_name = pango_font_description_get_family(ff.sys_desc);
|
||||
bool unseen = seen_families.find(sys_desc_family_name) == seen_families.end();
|
||||
|
||||
// Avoid sending duplicate SFNT font names due to a bug in Pango for macOS:
|
||||
// https://bugzilla.gnome.org/show_bug.cgi?id=762873
|
||||
if (unseen) {
|
||||
seen_families.insert(sys_desc_family_name);
|
||||
if (renamed_families.size()) renamed_families += ',';
|
||||
renamed_families += sys_desc_family_name;
|
||||
}
|
||||
|
||||
if (first && (best.user_desc == nullptr || pango_font_description_better_match(desc, best.user_desc, ff.user_desc))) {
|
||||
best = ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (resolved_families.size()) resolved_families += ',';
|
||||
resolved_families += renamed_families.size() ? renamed_families : family;
|
||||
first = false;
|
||||
}
|
||||
|
||||
PangoFontDescription* ret = pango_font_description_copy(best.sys_desc ? best.sys_desc : desc);
|
||||
pango_font_description_set_family(ret, resolved_families.c_str());
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Re-alloc the surface, destroying the previous.
|
||||
*/
|
||||
|
||||
void
|
||||
Canvas::resurface(Local<Object> canvas) {
|
||||
Nan::HandleScope scope;
|
||||
Local<Value> context;
|
||||
|
||||
backend()->recreateSurface();
|
||||
|
||||
// Reset context
|
||||
context = Nan::Get(canvas, Nan::New<String>("context").ToLocalChecked()).ToLocalChecked();
|
||||
if (!context->IsUndefined()) {
|
||||
Context2d *context2d = ObjectWrap::Unwrap<Context2d>(Nan::To<Object>(context).ToLocalChecked());
|
||||
cairo_t *prev = context2d->context();
|
||||
context2d->setContext(createCairoContext());
|
||||
context2d->resetState();
|
||||
cairo_destroy(prev);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around cairo_create()
|
||||
* (do not call cairo_create directly, call this instead)
|
||||
*/
|
||||
cairo_t*
|
||||
Canvas::createCairoContext() {
|
||||
cairo_t* ret = cairo_create(surface());
|
||||
cairo_set_line_width(ret, 1); // Cairo defaults to 2
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Construct an Error from the given cairo status.
|
||||
*/
|
||||
|
||||
Local<Value>
|
||||
Canvas::Error(cairo_status_t status) {
|
||||
return Exception::Error(Nan::New<String>(cairo_status_to_string(status)).ToLocalChecked());
|
||||
}
|
||||
80
node_modules/canvas/src/Canvas.h
generated
vendored
Normal file
80
node_modules/canvas/src/Canvas.h
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "backend/Backend.h"
|
||||
#include <cairo.h>
|
||||
#include "dll_visibility.h"
|
||||
#include <nan.h>
|
||||
#include <pango/pangocairo.h>
|
||||
#include <v8.h>
|
||||
#include <vector>
|
||||
#include <cstddef>
|
||||
|
||||
/*
|
||||
* Maxmimum states per context.
|
||||
* TODO: remove/resize
|
||||
*/
|
||||
|
||||
#ifndef CANVAS_MAX_STATES
|
||||
#define CANVAS_MAX_STATES 64
|
||||
#endif
|
||||
|
||||
/*
|
||||
* FontFace describes a font file in terms of one PangoFontDescription that
|
||||
* will resolve to it and one that the user describes it as (like @font-face)
|
||||
*/
|
||||
class FontFace {
|
||||
public:
|
||||
PangoFontDescription *sys_desc = nullptr;
|
||||
PangoFontDescription *user_desc = nullptr;
|
||||
};
|
||||
|
||||
/*
|
||||
* Canvas.
|
||||
*/
|
||||
|
||||
class Canvas: public Nan::ObjectWrap {
|
||||
public:
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(ToBuffer);
|
||||
static NAN_GETTER(GetType);
|
||||
static NAN_GETTER(GetStride);
|
||||
static NAN_GETTER(GetWidth);
|
||||
static NAN_GETTER(GetHeight);
|
||||
static NAN_SETTER(SetWidth);
|
||||
static NAN_SETTER(SetHeight);
|
||||
static NAN_METHOD(StreamPNGSync);
|
||||
static NAN_METHOD(StreamPDFSync);
|
||||
static NAN_METHOD(StreamJPEGSync);
|
||||
static NAN_METHOD(RegisterFont);
|
||||
static v8::Local<v8::Value> Error(cairo_status_t status);
|
||||
static void ToPngBufferAsync(uv_work_t *req);
|
||||
static void ToJpegBufferAsync(uv_work_t *req);
|
||||
static void ToBufferAsyncAfter(uv_work_t *req);
|
||||
static PangoWeight GetWeightFromCSSString(const char *weight);
|
||||
static PangoStyle GetStyleFromCSSString(const char *style);
|
||||
static PangoFontDescription *ResolveFontDescription(const PangoFontDescription *desc);
|
||||
|
||||
DLL_PUBLIC inline Backend* backend() { return _backend; }
|
||||
DLL_PUBLIC inline cairo_surface_t* surface(){ return backend()->getSurface(); }
|
||||
cairo_t* createCairoContext();
|
||||
|
||||
DLL_PUBLIC inline uint8_t *data(){ return cairo_image_surface_get_data(surface()); }
|
||||
DLL_PUBLIC inline int stride(){ return cairo_image_surface_get_stride(surface()); }
|
||||
DLL_PUBLIC inline std::size_t nBytes(){
|
||||
return static_cast<std::size_t>(getHeight()) * stride();
|
||||
}
|
||||
|
||||
DLL_PUBLIC inline int getWidth() { return backend()->getWidth(); }
|
||||
DLL_PUBLIC inline int getHeight() { return backend()->getHeight(); }
|
||||
|
||||
Canvas(Backend* backend);
|
||||
void resurface(v8::Local<v8::Object> canvas);
|
||||
|
||||
private:
|
||||
~Canvas();
|
||||
Backend* _backend;
|
||||
};
|
||||
23
node_modules/canvas/src/CanvasError.h
generated
vendored
Normal file
23
node_modules/canvas/src/CanvasError.h
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
class CanvasError {
|
||||
public:
|
||||
std::string message;
|
||||
std::string syscall;
|
||||
std::string path;
|
||||
int cerrno = 0;
|
||||
void set(const char* iMessage = NULL, const char* iSyscall = NULL, int iErrno = 0, const char* iPath = NULL) {
|
||||
if (iMessage) message.assign(iMessage);
|
||||
if (iSyscall) syscall.assign(iSyscall);
|
||||
cerrno = iErrno;
|
||||
if (iPath) path.assign(iPath);
|
||||
}
|
||||
void reset() {
|
||||
message.clear();
|
||||
syscall.clear();
|
||||
path.clear();
|
||||
cerrno = 0;
|
||||
}
|
||||
};
|
||||
123
node_modules/canvas/src/CanvasGradient.cc
generated
vendored
Normal file
123
node_modules/canvas/src/CanvasGradient.cc
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#include "CanvasGradient.h"
|
||||
|
||||
#include "Canvas.h"
|
||||
#include "color.h"
|
||||
|
||||
using namespace v8;
|
||||
|
||||
Nan::Persistent<FunctionTemplate> Gradient::constructor;
|
||||
|
||||
/*
|
||||
* Initialize CanvasGradient.
|
||||
*/
|
||||
|
||||
void
|
||||
Gradient::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Constructor
|
||||
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Gradient::New);
|
||||
constructor.Reset(ctor);
|
||||
ctor->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
ctor->SetClassName(Nan::New("CanvasGradient").ToLocalChecked());
|
||||
|
||||
// Prototype
|
||||
Nan::SetPrototypeMethod(ctor, "addColorStop", AddColorStop);
|
||||
Local<Context> ctx = Nan::GetCurrentContext();
|
||||
Nan::Set(target,
|
||||
Nan::New("CanvasGradient").ToLocalChecked(),
|
||||
ctor->GetFunction(ctx).ToLocalChecked());
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize a new CanvasGradient.
|
||||
*/
|
||||
|
||||
NAN_METHOD(Gradient::New) {
|
||||
if (!info.IsConstructCall()) {
|
||||
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
// Linear
|
||||
if (4 == info.Length()) {
|
||||
Gradient *grad = new Gradient(
|
||||
Nan::To<double>(info[0]).FromMaybe(0)
|
||||
, Nan::To<double>(info[1]).FromMaybe(0)
|
||||
, Nan::To<double>(info[2]).FromMaybe(0)
|
||||
, Nan::To<double>(info[3]).FromMaybe(0));
|
||||
grad->Wrap(info.This());
|
||||
info.GetReturnValue().Set(info.This());
|
||||
return;
|
||||
}
|
||||
|
||||
// Radial
|
||||
if (6 == info.Length()) {
|
||||
Gradient *grad = new Gradient(
|
||||
Nan::To<double>(info[0]).FromMaybe(0)
|
||||
, Nan::To<double>(info[1]).FromMaybe(0)
|
||||
, Nan::To<double>(info[2]).FromMaybe(0)
|
||||
, Nan::To<double>(info[3]).FromMaybe(0)
|
||||
, Nan::To<double>(info[4]).FromMaybe(0)
|
||||
, Nan::To<double>(info[5]).FromMaybe(0));
|
||||
grad->Wrap(info.This());
|
||||
info.GetReturnValue().Set(info.This());
|
||||
return;
|
||||
}
|
||||
|
||||
return Nan::ThrowTypeError("invalid arguments");
|
||||
}
|
||||
|
||||
/*
|
||||
* Add color stop.
|
||||
*/
|
||||
|
||||
NAN_METHOD(Gradient::AddColorStop) {
|
||||
if (!info[0]->IsNumber())
|
||||
return Nan::ThrowTypeError("offset required");
|
||||
if (!info[1]->IsString())
|
||||
return Nan::ThrowTypeError("color string required");
|
||||
|
||||
Gradient *grad = Nan::ObjectWrap::Unwrap<Gradient>(info.This());
|
||||
short ok;
|
||||
Nan::Utf8String str(info[1]);
|
||||
uint32_t rgba = rgba_from_string(*str, &ok);
|
||||
|
||||
if (ok) {
|
||||
rgba_t color = rgba_create(rgba);
|
||||
cairo_pattern_add_color_stop_rgba(
|
||||
grad->pattern()
|
||||
, Nan::To<double>(info[0]).FromMaybe(0)
|
||||
, color.r
|
||||
, color.g
|
||||
, color.b
|
||||
, color.a);
|
||||
} else {
|
||||
return Nan::ThrowTypeError("parse color failed");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize linear gradient.
|
||||
*/
|
||||
|
||||
Gradient::Gradient(double x0, double y0, double x1, double y1) {
|
||||
_pattern = cairo_pattern_create_linear(x0, y0, x1, y1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize radial gradient.
|
||||
*/
|
||||
|
||||
Gradient::Gradient(double x0, double y0, double r0, double x1, double y1, double r1) {
|
||||
_pattern = cairo_pattern_create_radial(x0, y0, r0, x1, y1, r1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Destroy the pattern.
|
||||
*/
|
||||
|
||||
Gradient::~Gradient() {
|
||||
cairo_pattern_destroy(_pattern);
|
||||
}
|
||||
22
node_modules/canvas/src/CanvasGradient.h
generated
vendored
Normal file
22
node_modules/canvas/src/CanvasGradient.h
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <nan.h>
|
||||
#include <v8.h>
|
||||
#include <cairo.h>
|
||||
|
||||
class Gradient: public Nan::ObjectWrap {
|
||||
public:
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(AddColorStop);
|
||||
Gradient(double x0, double y0, double x1, double y1);
|
||||
Gradient(double x0, double y0, double r0, double x1, double y1, double r1);
|
||||
inline cairo_pattern_t *pattern(){ return _pattern; }
|
||||
|
||||
private:
|
||||
~Gradient();
|
||||
cairo_pattern_t *_pattern;
|
||||
};
|
||||
101
node_modules/canvas/src/CanvasPattern.cc
generated
vendored
Normal file
101
node_modules/canvas/src/CanvasPattern.cc
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#include "CanvasPattern.h"
|
||||
|
||||
#include "Canvas.h"
|
||||
#include "Image.h"
|
||||
|
||||
using namespace v8;
|
||||
|
||||
const cairo_user_data_key_t *pattern_repeat_key;
|
||||
|
||||
Nan::Persistent<FunctionTemplate> Pattern::constructor;
|
||||
|
||||
/*
|
||||
* Initialize CanvasPattern.
|
||||
*/
|
||||
|
||||
void
|
||||
Pattern::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Constructor
|
||||
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Pattern::New);
|
||||
constructor.Reset(ctor);
|
||||
ctor->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
ctor->SetClassName(Nan::New("CanvasPattern").ToLocalChecked());
|
||||
|
||||
ctor->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
ctor->SetClassName(Nan::New("CanvasPattern").ToLocalChecked());
|
||||
|
||||
// Prototype
|
||||
Local<Context> ctx = Nan::GetCurrentContext();
|
||||
Nan::Set(target,
|
||||
Nan::New("CanvasPattern").ToLocalChecked(),
|
||||
ctor->GetFunction(ctx).ToLocalChecked());
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize a new CanvasPattern.
|
||||
*/
|
||||
|
||||
NAN_METHOD(Pattern::New) {
|
||||
if (!info.IsConstructCall()) {
|
||||
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
cairo_surface_t *surface;
|
||||
|
||||
Local<Object> obj = Nan::To<Object>(info[0]).ToLocalChecked();
|
||||
|
||||
// Image
|
||||
if (Nan::New(Image::constructor)->HasInstance(obj)) {
|
||||
Image *img = Nan::ObjectWrap::Unwrap<Image>(obj);
|
||||
if (!img->isComplete()) {
|
||||
return Nan::ThrowError("Image given has not completed loading");
|
||||
}
|
||||
surface = img->surface();
|
||||
|
||||
// Canvas
|
||||
} else if (Nan::New(Canvas::constructor)->HasInstance(obj)) {
|
||||
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(obj);
|
||||
surface = canvas->surface();
|
||||
// Invalid
|
||||
} else {
|
||||
return Nan::ThrowTypeError("Image or Canvas expected");
|
||||
}
|
||||
repeat_type_t repeat = REPEAT;
|
||||
if (0 == strcmp("no-repeat", *Nan::Utf8String(info[1]))) {
|
||||
repeat = NO_REPEAT;
|
||||
} else if (0 == strcmp("repeat-x", *Nan::Utf8String(info[1]))) {
|
||||
repeat = REPEAT_X;
|
||||
} else if (0 == strcmp("repeat-y", *Nan::Utf8String(info[1]))) {
|
||||
repeat = REPEAT_Y;
|
||||
}
|
||||
Pattern *pattern = new Pattern(surface, repeat);
|
||||
pattern->Wrap(info.This());
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize pattern.
|
||||
*/
|
||||
|
||||
Pattern::Pattern(cairo_surface_t *surface, repeat_type_t repeat) {
|
||||
_pattern = cairo_pattern_create_for_surface(surface);
|
||||
_repeat = repeat;
|
||||
cairo_pattern_set_user_data(_pattern, pattern_repeat_key, &_repeat, NULL);
|
||||
}
|
||||
|
||||
repeat_type_t Pattern::get_repeat_type_for_cairo_pattern(cairo_pattern_t *pattern) {
|
||||
void *ud = cairo_pattern_get_user_data(pattern, pattern_repeat_key);
|
||||
return *reinterpret_cast<repeat_type_t*>(ud);
|
||||
}
|
||||
|
||||
/*
|
||||
* Destroy the pattern.
|
||||
*/
|
||||
|
||||
Pattern::~Pattern() {
|
||||
cairo_pattern_destroy(_pattern);
|
||||
}
|
||||
34
node_modules/canvas/src/CanvasPattern.h
generated
vendored
Normal file
34
node_modules/canvas/src/CanvasPattern.h
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) 2011 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cairo.h>
|
||||
#include <nan.h>
|
||||
#include <v8.h>
|
||||
|
||||
/*
|
||||
* Canvas types.
|
||||
*/
|
||||
|
||||
typedef enum {
|
||||
NO_REPEAT, // match CAIRO_EXTEND_NONE
|
||||
REPEAT, // match CAIRO_EXTEND_REPEAT
|
||||
REPEAT_X, // needs custom processing
|
||||
REPEAT_Y // needs custom processing
|
||||
} repeat_type_t;
|
||||
|
||||
extern const cairo_user_data_key_t *pattern_repeat_key;
|
||||
|
||||
class Pattern: public Nan::ObjectWrap {
|
||||
public:
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static repeat_type_t get_repeat_type_for_cairo_pattern(cairo_pattern_t *pattern);
|
||||
Pattern(cairo_surface_t *surface, repeat_type_t repeat);
|
||||
inline cairo_pattern_t *pattern(){ return _pattern; }
|
||||
private:
|
||||
~Pattern();
|
||||
cairo_pattern_t *_pattern;
|
||||
repeat_type_t _repeat;
|
||||
};
|
||||
3108
node_modules/canvas/src/CanvasRenderingContext2d.cc
generated
vendored
Normal file
3108
node_modules/canvas/src/CanvasRenderingContext2d.cc
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
203
node_modules/canvas/src/CanvasRenderingContext2d.h
generated
vendored
Normal file
203
node_modules/canvas/src/CanvasRenderingContext2d.h
generated
vendored
Normal file
@@ -0,0 +1,203 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "cairo.h"
|
||||
#include "Canvas.h"
|
||||
#include "color.h"
|
||||
#include "nan.h"
|
||||
#include <pango/pangocairo.h>
|
||||
|
||||
typedef enum {
|
||||
TEXT_DRAW_PATHS,
|
||||
TEXT_DRAW_GLYPHS
|
||||
} canvas_draw_mode_t;
|
||||
|
||||
/*
|
||||
* State struct.
|
||||
*
|
||||
* Used in conjunction with Save() / Restore() since
|
||||
* cairo's gstate maintains only a single source pattern at a time.
|
||||
*/
|
||||
|
||||
typedef struct {
|
||||
rgba_t fill;
|
||||
rgba_t stroke;
|
||||
cairo_filter_t patternQuality;
|
||||
cairo_pattern_t *fillPattern;
|
||||
cairo_pattern_t *strokePattern;
|
||||
cairo_pattern_t *fillGradient;
|
||||
cairo_pattern_t *strokeGradient;
|
||||
float globalAlpha;
|
||||
short textAlignment;
|
||||
short textBaseline;
|
||||
rgba_t shadow;
|
||||
int shadowBlur;
|
||||
double shadowOffsetX;
|
||||
double shadowOffsetY;
|
||||
canvas_draw_mode_t textDrawingMode;
|
||||
PangoFontDescription *fontDescription;
|
||||
bool imageSmoothingEnabled;
|
||||
} canvas_state_t;
|
||||
|
||||
/*
|
||||
* Equivalent to a PangoRectangle but holds floats instead of ints
|
||||
* (software pixels are stored here instead of pango units)
|
||||
*
|
||||
* Should be compatible with PANGO_ASCENT, PANGO_LBEARING, etc.
|
||||
*/
|
||||
|
||||
typedef struct {
|
||||
float x;
|
||||
float y;
|
||||
float width;
|
||||
float height;
|
||||
} float_rectangle;
|
||||
|
||||
void state_assign_fontFamily(canvas_state_t *state, const char *str);
|
||||
|
||||
class Context2d: public Nan::ObjectWrap {
|
||||
public:
|
||||
short stateno;
|
||||
canvas_state_t *states[CANVAS_MAX_STATES];
|
||||
canvas_state_t *state;
|
||||
Context2d(Canvas *canvas);
|
||||
static Nan::Persistent<v8::Function> _DOMMatrix;
|
||||
static Nan::Persistent<v8::Function> _parseFont;
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(SaveExternalModules);
|
||||
static NAN_METHOD(DrawImage);
|
||||
static NAN_METHOD(PutImageData);
|
||||
static NAN_METHOD(Save);
|
||||
static NAN_METHOD(Restore);
|
||||
static NAN_METHOD(Rotate);
|
||||
static NAN_METHOD(Translate);
|
||||
static NAN_METHOD(Scale);
|
||||
static NAN_METHOD(Transform);
|
||||
static NAN_METHOD(GetTransform);
|
||||
static NAN_METHOD(ResetTransform);
|
||||
static NAN_METHOD(SetTransform);
|
||||
static NAN_METHOD(IsPointInPath);
|
||||
static NAN_METHOD(BeginPath);
|
||||
static NAN_METHOD(ClosePath);
|
||||
static NAN_METHOD(AddPage);
|
||||
static NAN_METHOD(Clip);
|
||||
static NAN_METHOD(Fill);
|
||||
static NAN_METHOD(Stroke);
|
||||
static NAN_METHOD(FillText);
|
||||
static NAN_METHOD(StrokeText);
|
||||
static NAN_METHOD(SetFont);
|
||||
static NAN_METHOD(SetFillColor);
|
||||
static NAN_METHOD(SetStrokeColor);
|
||||
static NAN_METHOD(SetStrokePattern);
|
||||
static NAN_METHOD(SetTextAlignment);
|
||||
static NAN_METHOD(SetLineDash);
|
||||
static NAN_METHOD(GetLineDash);
|
||||
static NAN_METHOD(MeasureText);
|
||||
static NAN_METHOD(BezierCurveTo);
|
||||
static NAN_METHOD(QuadraticCurveTo);
|
||||
static NAN_METHOD(LineTo);
|
||||
static NAN_METHOD(MoveTo);
|
||||
static NAN_METHOD(FillRect);
|
||||
static NAN_METHOD(StrokeRect);
|
||||
static NAN_METHOD(ClearRect);
|
||||
static NAN_METHOD(Rect);
|
||||
static NAN_METHOD(Arc);
|
||||
static NAN_METHOD(ArcTo);
|
||||
static NAN_METHOD(Ellipse);
|
||||
static NAN_METHOD(GetImageData);
|
||||
static NAN_METHOD(CreateImageData);
|
||||
static NAN_METHOD(GetStrokeColor);
|
||||
static NAN_METHOD(CreatePattern);
|
||||
static NAN_METHOD(CreateLinearGradient);
|
||||
static NAN_METHOD(CreateRadialGradient);
|
||||
static NAN_GETTER(GetFormat);
|
||||
static NAN_GETTER(GetPatternQuality);
|
||||
static NAN_GETTER(GetImageSmoothingEnabled);
|
||||
static NAN_GETTER(GetGlobalCompositeOperation);
|
||||
static NAN_GETTER(GetGlobalAlpha);
|
||||
static NAN_GETTER(GetShadowColor);
|
||||
static NAN_GETTER(GetMiterLimit);
|
||||
static NAN_GETTER(GetLineCap);
|
||||
static NAN_GETTER(GetLineJoin);
|
||||
static NAN_GETTER(GetLineWidth);
|
||||
static NAN_GETTER(GetLineDashOffset);
|
||||
static NAN_GETTER(GetShadowOffsetX);
|
||||
static NAN_GETTER(GetShadowOffsetY);
|
||||
static NAN_GETTER(GetShadowBlur);
|
||||
static NAN_GETTER(GetAntiAlias);
|
||||
static NAN_GETTER(GetTextDrawingMode);
|
||||
static NAN_GETTER(GetQuality);
|
||||
static NAN_GETTER(GetCurrentTransform);
|
||||
static NAN_GETTER(GetFillStyle);
|
||||
static NAN_GETTER(GetStrokeStyle);
|
||||
static NAN_GETTER(GetFont);
|
||||
static NAN_GETTER(GetTextBaseline);
|
||||
static NAN_GETTER(GetTextAlign);
|
||||
static NAN_SETTER(SetPatternQuality);
|
||||
static NAN_SETTER(SetImageSmoothingEnabled);
|
||||
static NAN_SETTER(SetGlobalCompositeOperation);
|
||||
static NAN_SETTER(SetGlobalAlpha);
|
||||
static NAN_SETTER(SetShadowColor);
|
||||
static NAN_SETTER(SetMiterLimit);
|
||||
static NAN_SETTER(SetLineCap);
|
||||
static NAN_SETTER(SetLineJoin);
|
||||
static NAN_SETTER(SetLineWidth);
|
||||
static NAN_SETTER(SetLineDashOffset);
|
||||
static NAN_SETTER(SetShadowOffsetX);
|
||||
static NAN_SETTER(SetShadowOffsetY);
|
||||
static NAN_SETTER(SetShadowBlur);
|
||||
static NAN_SETTER(SetAntiAlias);
|
||||
static NAN_SETTER(SetTextDrawingMode);
|
||||
static NAN_SETTER(SetQuality);
|
||||
static NAN_SETTER(SetCurrentTransform);
|
||||
static NAN_SETTER(SetFillStyle);
|
||||
static NAN_SETTER(SetStrokeStyle);
|
||||
static NAN_SETTER(SetFont);
|
||||
static NAN_SETTER(SetTextBaseline);
|
||||
static NAN_SETTER(SetTextAlign);
|
||||
inline void setContext(cairo_t *ctx) { _context = ctx; }
|
||||
inline cairo_t *context(){ return _context; }
|
||||
inline Canvas *canvas(){ return _canvas; }
|
||||
inline bool hasShadow();
|
||||
void inline setSourceRGBA(rgba_t color);
|
||||
void inline setSourceRGBA(cairo_t *ctx, rgba_t color);
|
||||
void setTextPath(double x, double y);
|
||||
void blur(cairo_surface_t *surface, int radius);
|
||||
void shadow(void (fn)(cairo_t *cr));
|
||||
void shadowStart();
|
||||
void shadowApply();
|
||||
void savePath();
|
||||
void restorePath();
|
||||
void saveState();
|
||||
void restoreState();
|
||||
void inline setFillRule(v8::Local<v8::Value> value);
|
||||
void fill(bool preserve = false);
|
||||
void stroke(bool preserve = false);
|
||||
void save();
|
||||
void restore();
|
||||
void setFontFromState();
|
||||
void resetState(bool init = false);
|
||||
inline PangoLayout *layout(){ return _layout; }
|
||||
|
||||
private:
|
||||
~Context2d();
|
||||
void _resetPersistentHandles();
|
||||
v8::Local<v8::Value> _getFillColor();
|
||||
v8::Local<v8::Value> _getStrokeColor();
|
||||
void _setFillColor(v8::Local<v8::Value> arg);
|
||||
void _setFillPattern(v8::Local<v8::Value> arg);
|
||||
void _setStrokeColor(v8::Local<v8::Value> arg);
|
||||
void _setStrokePattern(v8::Local<v8::Value> arg);
|
||||
Nan::Persistent<v8::Value> _fillStyle;
|
||||
Nan::Persistent<v8::Value> _strokeStyle;
|
||||
Nan::Persistent<v8::Value> _font;
|
||||
Nan::Persistent<v8::Value> _textBaseline;
|
||||
Nan::Persistent<v8::Value> _textAlign;
|
||||
Canvas *_canvas;
|
||||
cairo_t *_context;
|
||||
cairo_path_t *_path;
|
||||
PangoLayout *_layout;
|
||||
};
|
||||
1402
node_modules/canvas/src/Image.cc
generated
vendored
Normal file
1402
node_modules/canvas/src/Image.cc
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
127
node_modules/canvas/src/Image.h
generated
vendored
Normal file
127
node_modules/canvas/src/Image.h
generated
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cairo.h>
|
||||
#include "CanvasError.h"
|
||||
#include <functional>
|
||||
#include <nan.h>
|
||||
#include <stdint.h> // node < 7 uses libstdc++ on macOS which lacks complete c++11
|
||||
#include <v8.h>
|
||||
|
||||
#ifdef HAVE_JPEG
|
||||
#include <jpeglib.h>
|
||||
#include <jerror.h>
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_GIF
|
||||
#include <gif_lib.h>
|
||||
|
||||
#if GIFLIB_MAJOR > 5 || GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1
|
||||
#define GIF_CLOSE_FILE(gif) DGifCloseFile(gif, NULL)
|
||||
#else
|
||||
#define GIF_CLOSE_FILE(gif) DGifCloseFile(gif)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_RSVG
|
||||
#include <librsvg/rsvg.h>
|
||||
// librsvg <= 2.36.1, identified by undefined macro, needs an extra include
|
||||
#ifndef LIBRSVG_CHECK_VERSION
|
||||
#include <librsvg/rsvg-cairo.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
using JPEGDecodeL = std::function<uint32_t (uint8_t* const src)>;
|
||||
|
||||
class Image: public Nan::ObjectWrap {
|
||||
public:
|
||||
char *filename;
|
||||
int width, height;
|
||||
int naturalWidth, naturalHeight;
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static NAN_GETTER(GetComplete);
|
||||
static NAN_GETTER(GetWidth);
|
||||
static NAN_GETTER(GetHeight);
|
||||
static NAN_GETTER(GetNaturalWidth);
|
||||
static NAN_GETTER(GetNaturalHeight);
|
||||
static NAN_GETTER(GetDataMode);
|
||||
static NAN_SETTER(SetDataMode);
|
||||
static NAN_SETTER(SetWidth);
|
||||
static NAN_SETTER(SetHeight);
|
||||
static NAN_METHOD(GetSource);
|
||||
static NAN_METHOD(SetSource);
|
||||
inline uint8_t *data(){ return cairo_image_surface_get_data(_surface); }
|
||||
inline int stride(){ return cairo_image_surface_get_stride(_surface); }
|
||||
static int isPNG(uint8_t *data);
|
||||
static int isJPEG(uint8_t *data);
|
||||
static int isGIF(uint8_t *data);
|
||||
static int isSVG(uint8_t *data, unsigned len);
|
||||
static int isBMP(uint8_t *data, unsigned len);
|
||||
static cairo_status_t readPNG(void *closure, unsigned char *data, unsigned len);
|
||||
inline int isComplete(){ return COMPLETE == state; }
|
||||
cairo_surface_t *surface();
|
||||
cairo_status_t loadSurface();
|
||||
cairo_status_t loadFromBuffer(uint8_t *buf, unsigned len);
|
||||
cairo_status_t loadPNGFromBuffer(uint8_t *buf);
|
||||
cairo_status_t loadPNG();
|
||||
void clearData();
|
||||
#ifdef HAVE_RSVG
|
||||
cairo_status_t loadSVGFromBuffer(uint8_t *buf, unsigned len);
|
||||
cairo_status_t loadSVG(FILE *stream);
|
||||
cairo_status_t renderSVGToSurface();
|
||||
#endif
|
||||
#ifdef HAVE_GIF
|
||||
cairo_status_t loadGIFFromBuffer(uint8_t *buf, unsigned len);
|
||||
cairo_status_t loadGIF(FILE *stream);
|
||||
#endif
|
||||
#ifdef HAVE_JPEG
|
||||
cairo_status_t loadJPEGFromBuffer(uint8_t *buf, unsigned len);
|
||||
cairo_status_t loadJPEG(FILE *stream);
|
||||
void jpegToARGB(jpeg_decompress_struct* args, uint8_t* data, uint8_t* src, JPEGDecodeL decode);
|
||||
cairo_status_t decodeJPEGIntoSurface(jpeg_decompress_struct *info);
|
||||
cairo_status_t decodeJPEGBufferIntoMimeSurface(uint8_t *buf, unsigned len);
|
||||
cairo_status_t assignDataAsMime(uint8_t *data, int len, const char *mime_type);
|
||||
#endif
|
||||
cairo_status_t loadBMPFromBuffer(uint8_t *buf, unsigned len);
|
||||
cairo_status_t loadBMP(FILE *stream);
|
||||
CanvasError errorInfo;
|
||||
void loaded();
|
||||
cairo_status_t load();
|
||||
Image();
|
||||
|
||||
enum {
|
||||
DEFAULT
|
||||
, LOADING
|
||||
, COMPLETE
|
||||
} state;
|
||||
|
||||
enum data_mode_t {
|
||||
DATA_IMAGE = 1
|
||||
, DATA_MIME = 2
|
||||
} data_mode;
|
||||
|
||||
typedef enum {
|
||||
UNKNOWN
|
||||
, GIF
|
||||
, JPEG
|
||||
, PNG
|
||||
, SVG
|
||||
} type;
|
||||
|
||||
static type extension(const char *filename);
|
||||
|
||||
private:
|
||||
cairo_surface_t *_surface;
|
||||
uint8_t *_data = nullptr;
|
||||
int _data_len;
|
||||
#ifdef HAVE_RSVG
|
||||
RsvgHandle *_rsvg;
|
||||
bool _is_svg;
|
||||
int _svg_last_width;
|
||||
int _svg_last_height;
|
||||
#endif
|
||||
~Image();
|
||||
};
|
||||
140
node_modules/canvas/src/ImageData.cc
generated
vendored
Normal file
140
node_modules/canvas/src/ImageData.cc
generated
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#include "ImageData.h"
|
||||
|
||||
#include "Util.h"
|
||||
|
||||
using namespace v8;
|
||||
|
||||
Nan::Persistent<FunctionTemplate> ImageData::constructor;
|
||||
|
||||
/*
|
||||
* Initialize ImageData.
|
||||
*/
|
||||
|
||||
void
|
||||
ImageData::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Constructor
|
||||
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(ImageData::New);
|
||||
constructor.Reset(ctor);
|
||||
ctor->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
ctor->SetClassName(Nan::New("ImageData").ToLocalChecked());
|
||||
|
||||
// Prototype
|
||||
Local<ObjectTemplate> proto = ctor->PrototypeTemplate();
|
||||
SetProtoAccessor(proto, Nan::New("width").ToLocalChecked(), GetWidth, NULL, ctor);
|
||||
SetProtoAccessor(proto, Nan::New("height").ToLocalChecked(), GetHeight, NULL, ctor);
|
||||
Local<Context> ctx = Nan::GetCurrentContext();
|
||||
Nan::Set(target, Nan::New("ImageData").ToLocalChecked(), ctor->GetFunction(ctx).ToLocalChecked());
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize a new ImageData object.
|
||||
*/
|
||||
|
||||
NAN_METHOD(ImageData::New) {
|
||||
if (!info.IsConstructCall()) {
|
||||
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
|
||||
}
|
||||
|
||||
Local<TypedArray> dataArray;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
int length;
|
||||
|
||||
if (info[0]->IsUint32() && info[1]->IsUint32()) {
|
||||
width = Nan::To<uint32_t>(info[0]).FromMaybe(0);
|
||||
if (width == 0) {
|
||||
Nan::ThrowRangeError("The source width is zero.");
|
||||
return;
|
||||
}
|
||||
height = Nan::To<uint32_t>(info[1]).FromMaybe(0);
|
||||
if (height == 0) {
|
||||
Nan::ThrowRangeError("The source height is zero.");
|
||||
return;
|
||||
}
|
||||
length = width * height * 4; // ImageData(w, h) constructor assumes 4 BPP; documented.
|
||||
|
||||
dataArray = Uint8ClampedArray::New(ArrayBuffer::New(Isolate::GetCurrent(), length), 0, length);
|
||||
|
||||
} else if (info[0]->IsUint8ClampedArray() && info[1]->IsUint32()) {
|
||||
dataArray = info[0].As<Uint8ClampedArray>();
|
||||
|
||||
length = dataArray->Length();
|
||||
if (length == 0) {
|
||||
Nan::ThrowRangeError("The input data has a zero byte length.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't assert that the ImageData length is a multiple of four because some
|
||||
// data formats are not 4 BPP.
|
||||
|
||||
width = Nan::To<uint32_t>(info[1]).FromMaybe(0);
|
||||
if (width == 0) {
|
||||
Nan::ThrowRangeError("The source width is zero.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't assert that the byte length is a multiple of 4 * width, ditto.
|
||||
|
||||
if (info[2]->IsUint32()) { // Explicit height given
|
||||
height = Nan::To<uint32_t>(info[2]).FromMaybe(0);
|
||||
} else { // Calculate height assuming 4 BPP
|
||||
int size = length / 4;
|
||||
height = size / width;
|
||||
}
|
||||
|
||||
} else if (info[0]->IsUint16Array() && info[1]->IsUint32()) { // Intended for RGB16_565 format
|
||||
dataArray = info[0].As<Uint16Array>();
|
||||
|
||||
length = dataArray->Length();
|
||||
if (length == 0) {
|
||||
Nan::ThrowRangeError("The input data has a zero byte length.");
|
||||
return;
|
||||
}
|
||||
|
||||
width = Nan::To<uint32_t>(info[1]).FromMaybe(0);
|
||||
if (width == 0) {
|
||||
Nan::ThrowRangeError("The source width is zero.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (info[2]->IsUint32()) { // Explicit height given
|
||||
height = Nan::To<uint32_t>(info[2]).FromMaybe(0);
|
||||
} else { // Calculate height assuming 2 BPP
|
||||
int size = length / 2;
|
||||
height = size / width;
|
||||
}
|
||||
|
||||
} else {
|
||||
Nan::ThrowTypeError("Expected (Uint8ClampedArray, width[, height]), (Uint16Array, width[, height]) or (width, height)");
|
||||
return;
|
||||
}
|
||||
|
||||
Nan::TypedArrayContents<uint8_t> dataPtr(dataArray);
|
||||
|
||||
ImageData *imageData = new ImageData(reinterpret_cast<uint8_t*>(*dataPtr), width, height);
|
||||
imageData->Wrap(info.This());
|
||||
Nan::Set(info.This(), Nan::New("data").ToLocalChecked(), dataArray).Check();
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
/*
|
||||
* Get width.
|
||||
*/
|
||||
|
||||
NAN_GETTER(ImageData::GetWidth) {
|
||||
ImageData *imageData = Nan::ObjectWrap::Unwrap<ImageData>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<Number>(imageData->width()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Get height.
|
||||
*/
|
||||
|
||||
NAN_GETTER(ImageData::GetHeight) {
|
||||
ImageData *imageData = Nan::ObjectWrap::Unwrap<ImageData>(info.This());
|
||||
info.GetReturnValue().Set(Nan::New<Number>(imageData->height()));
|
||||
}
|
||||
27
node_modules/canvas/src/ImageData.h
generated
vendored
Normal file
27
node_modules/canvas/src/ImageData.h
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <nan.h>
|
||||
#include <stdint.h> // node < 7 uses libstdc++ on macOS which lacks complete c++11
|
||||
#include <v8.h>
|
||||
|
||||
class ImageData: public Nan::ObjectWrap {
|
||||
public:
|
||||
static Nan::Persistent<v8::FunctionTemplate> constructor;
|
||||
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
|
||||
static NAN_METHOD(New);
|
||||
static NAN_GETTER(GetWidth);
|
||||
static NAN_GETTER(GetHeight);
|
||||
|
||||
inline int width() { return _width; }
|
||||
inline int height() { return _height; }
|
||||
inline uint8_t *data() { return _data; }
|
||||
ImageData(uint8_t *data, int width, int height) : _width(width), _height(height), _data(data) {}
|
||||
|
||||
private:
|
||||
int _width;
|
||||
int _height;
|
||||
uint8_t *_data;
|
||||
|
||||
};
|
||||
167
node_modules/canvas/src/JPEGStream.h
generated
vendored
Normal file
167
node_modules/canvas/src/JPEGStream.h
generated
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
#pragma once
|
||||
|
||||
#include "closure.h"
|
||||
#include <jpeglib.h>
|
||||
#include <jerror.h>
|
||||
|
||||
/*
|
||||
* Expanded data destination object for closure output,
|
||||
* inspired by IJG's jdatadst.c
|
||||
*/
|
||||
|
||||
struct closure_destination_mgr {
|
||||
jpeg_destination_mgr pub;
|
||||
JpegClosure* closure;
|
||||
JOCTET *buffer;
|
||||
int bufsize;
|
||||
};
|
||||
|
||||
void
|
||||
init_closure_destination(j_compress_ptr cinfo){
|
||||
// we really don't have to do anything here
|
||||
}
|
||||
|
||||
boolean
|
||||
empty_closure_output_buffer(j_compress_ptr cinfo){
|
||||
Nan::HandleScope scope;
|
||||
Nan::AsyncResource async("canvas:empty_closure_output_buffer");
|
||||
closure_destination_mgr *dest = (closure_destination_mgr *) cinfo->dest;
|
||||
|
||||
v8::Local<v8::Object> buf = Nan::NewBuffer((char *)dest->buffer, dest->bufsize).ToLocalChecked();
|
||||
|
||||
// emit "data"
|
||||
v8::Local<v8::Value> argv[2] = {
|
||||
Nan::Null()
|
||||
, buf
|
||||
};
|
||||
dest->closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
|
||||
|
||||
dest->buffer = (JOCTET *)malloc(dest->bufsize);
|
||||
cinfo->dest->next_output_byte = dest->buffer;
|
||||
cinfo->dest->free_in_buffer = dest->bufsize;
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
term_closure_destination(j_compress_ptr cinfo){
|
||||
Nan::HandleScope scope;
|
||||
Nan::AsyncResource async("canvas:term_closure_destination");
|
||||
closure_destination_mgr *dest = (closure_destination_mgr *) cinfo->dest;
|
||||
|
||||
/* emit remaining data */
|
||||
v8::Local<v8::Object> buf = Nan::NewBuffer((char *)dest->buffer, dest->bufsize - dest->pub.free_in_buffer).ToLocalChecked();
|
||||
|
||||
v8::Local<v8::Value> data_argv[2] = {
|
||||
Nan::Null()
|
||||
, buf
|
||||
};
|
||||
dest->closure->cb.Call(sizeof data_argv / sizeof *data_argv, data_argv, &async);
|
||||
|
||||
// emit "end"
|
||||
v8::Local<v8::Value> end_argv[2] = {
|
||||
Nan::Null()
|
||||
, Nan::Null()
|
||||
};
|
||||
dest->closure->cb.Call(sizeof end_argv / sizeof *end_argv, end_argv, &async);
|
||||
}
|
||||
|
||||
void
|
||||
jpeg_closure_dest(j_compress_ptr cinfo, JpegClosure* closure, int bufsize){
|
||||
closure_destination_mgr * dest;
|
||||
|
||||
/* The destination object is made permanent so that multiple JPEG images
|
||||
* can be written to the same buffer without re-executing jpeg_mem_dest.
|
||||
*/
|
||||
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
|
||||
cinfo->dest = (struct jpeg_destination_mgr *)
|
||||
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
|
||||
sizeof(closure_destination_mgr));
|
||||
}
|
||||
|
||||
dest = (closure_destination_mgr *) cinfo->dest;
|
||||
|
||||
cinfo->dest->init_destination = &init_closure_destination;
|
||||
cinfo->dest->empty_output_buffer = &empty_closure_output_buffer;
|
||||
cinfo->dest->term_destination = &term_closure_destination;
|
||||
|
||||
dest->closure = closure;
|
||||
dest->bufsize = bufsize;
|
||||
dest->buffer = (JOCTET *)malloc(bufsize);
|
||||
|
||||
cinfo->dest->next_output_byte = dest->buffer;
|
||||
cinfo->dest->free_in_buffer = dest->bufsize;
|
||||
}
|
||||
|
||||
void encode_jpeg(jpeg_compress_struct cinfo, cairo_surface_t *surface, int quality, bool progressive, int chromaHSampFactor, int chromaVSampFactor) {
|
||||
int w = cairo_image_surface_get_width(surface);
|
||||
int h = cairo_image_surface_get_height(surface);
|
||||
|
||||
cinfo.in_color_space = JCS_RGB;
|
||||
cinfo.input_components = 3;
|
||||
cinfo.image_width = w;
|
||||
cinfo.image_height = h;
|
||||
jpeg_set_defaults(&cinfo);
|
||||
if (progressive)
|
||||
jpeg_simple_progression(&cinfo);
|
||||
jpeg_set_quality(&cinfo, quality, (quality < 25) ? 0 : 1);
|
||||
cinfo.comp_info[0].h_samp_factor = chromaHSampFactor;
|
||||
cinfo.comp_info[0].v_samp_factor = chromaVSampFactor;
|
||||
|
||||
JSAMPROW slr;
|
||||
jpeg_start_compress(&cinfo, TRUE);
|
||||
unsigned char *dst;
|
||||
unsigned int *src = (unsigned int *)cairo_image_surface_get_data(surface);
|
||||
int sl = 0;
|
||||
dst = (unsigned char *)malloc(w * 3);
|
||||
while (sl < h) {
|
||||
unsigned char *dp = dst;
|
||||
int x = 0;
|
||||
while (x < w) {
|
||||
dp[0] = (*src >> 16) & 255;
|
||||
dp[1] = (*src >> 8) & 255;
|
||||
dp[2] = *src & 255;
|
||||
src++;
|
||||
dp += 3;
|
||||
x++;
|
||||
}
|
||||
slr = dst;
|
||||
jpeg_write_scanlines(&cinfo, &slr, 1);
|
||||
sl++;
|
||||
}
|
||||
free(dst);
|
||||
jpeg_finish_compress(&cinfo);
|
||||
jpeg_destroy_compress(&cinfo);
|
||||
}
|
||||
|
||||
void
|
||||
write_to_jpeg_stream(cairo_surface_t *surface, int bufsize, JpegClosure* closure) {
|
||||
jpeg_compress_struct cinfo;
|
||||
jpeg_error_mgr jerr;
|
||||
cinfo.err = jpeg_std_error(&jerr);
|
||||
jpeg_create_compress(&cinfo);
|
||||
jpeg_closure_dest(&cinfo, closure, bufsize);
|
||||
encode_jpeg(
|
||||
cinfo,
|
||||
surface,
|
||||
closure->quality,
|
||||
closure->progressive,
|
||||
closure->chromaSubsampling,
|
||||
closure->chromaSubsampling);
|
||||
}
|
||||
|
||||
void
|
||||
write_to_jpeg_buffer(cairo_surface_t* surface, JpegClosure* closure) {
|
||||
jpeg_compress_struct cinfo;
|
||||
jpeg_error_mgr jerr;
|
||||
cinfo.err = jpeg_std_error(&jerr);
|
||||
jpeg_create_compress(&cinfo);
|
||||
cinfo.client_data = closure;
|
||||
cinfo.dest = closure->jpeg_dest_mgr;
|
||||
encode_jpeg(
|
||||
cinfo,
|
||||
surface,
|
||||
closure->quality,
|
||||
closure->progressive,
|
||||
closure->chromaSubsampling,
|
||||
closure->chromaSubsampling);
|
||||
}
|
||||
292
node_modules/canvas/src/PNG.h
generated
vendored
Normal file
292
node_modules/canvas/src/PNG.h
generated
vendored
Normal file
@@ -0,0 +1,292 @@
|
||||
#pragma once
|
||||
|
||||
#include <cairo.h>
|
||||
#include "closure.h"
|
||||
#include <cmath> // round
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <png.h>
|
||||
#include <pngconf.h>
|
||||
|
||||
#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
|
||||
#define likely(expr) (__builtin_expect (!!(expr), 1))
|
||||
#define unlikely(expr) (__builtin_expect (!!(expr), 0))
|
||||
#else
|
||||
#define likely(expr) (expr)
|
||||
#define unlikely(expr) (expr)
|
||||
#endif
|
||||
|
||||
static void canvas_png_flush(png_structp png_ptr) {
|
||||
/* Do nothing; fflush() is said to be just a waste of energy. */
|
||||
(void) png_ptr; /* Stifle compiler warning */
|
||||
}
|
||||
|
||||
/* Converts native endian xRGB => RGBx bytes */
|
||||
static void canvas_convert_data_to_bytes(png_structp png, png_row_infop row_info, png_bytep data) {
|
||||
unsigned int i;
|
||||
|
||||
for (i = 0; i < row_info->rowbytes; i += 4) {
|
||||
uint8_t *b = &data[i];
|
||||
uint32_t pixel;
|
||||
|
||||
memcpy(&pixel, b, sizeof (uint32_t));
|
||||
|
||||
b[0] = (pixel & 0xff0000) >> 16;
|
||||
b[1] = (pixel & 0x00ff00) >> 8;
|
||||
b[2] = (pixel & 0x0000ff) >> 0;
|
||||
b[3] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Unpremultiplies data and converts native endian ARGB => RGBA bytes */
|
||||
static void canvas_unpremultiply_data(png_structp png, png_row_infop row_info, png_bytep data) {
|
||||
unsigned int i;
|
||||
|
||||
for (i = 0; i < row_info->rowbytes; i += 4) {
|
||||
uint8_t *b = &data[i];
|
||||
uint32_t pixel;
|
||||
uint8_t alpha;
|
||||
|
||||
memcpy(&pixel, b, sizeof (uint32_t));
|
||||
alpha = (pixel & 0xff000000) >> 24;
|
||||
if (alpha == 0) {
|
||||
b[0] = b[1] = b[2] = b[3] = 0;
|
||||
} else {
|
||||
b[0] = (((pixel & 0xff0000) >> 16) * 255 + alpha / 2) / alpha;
|
||||
b[1] = (((pixel & 0x00ff00) >> 8) * 255 + alpha / 2) / alpha;
|
||||
b[2] = (((pixel & 0x0000ff) >> 0) * 255 + alpha / 2) / alpha;
|
||||
b[3] = alpha;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Converts RGB16_565 format data to RGBA32 */
|
||||
static void canvas_convert_565_to_888(png_structp png, png_row_infop row_info, png_bytep data) {
|
||||
// Loop in reverse to unpack in-place.
|
||||
for (ptrdiff_t col = row_info->width - 1; col >= 0; col--) {
|
||||
uint8_t* src = &data[col * sizeof(uint16_t)];
|
||||
uint8_t* dst = &data[col * 3];
|
||||
uint16_t pixel;
|
||||
|
||||
memcpy(&pixel, src, sizeof(uint16_t));
|
||||
|
||||
// Convert and rescale to the full 0-255 range
|
||||
// See http://stackoverflow.com/a/29326693
|
||||
const uint8_t red5 = (pixel & 0xF800) >> 11;
|
||||
const uint8_t green6 = (pixel & 0x7E0) >> 5;
|
||||
const uint8_t blue5 = (pixel & 0x001F);
|
||||
|
||||
dst[0] = ((red5 * 255 + 15) / 31);
|
||||
dst[1] = ((green6 * 255 + 31) / 63);
|
||||
dst[2] = ((blue5 * 255 + 15) / 31);
|
||||
}
|
||||
}
|
||||
|
||||
struct canvas_png_write_closure_t {
|
||||
cairo_write_func_t write_func;
|
||||
PngClosure* closure;
|
||||
};
|
||||
|
||||
#ifdef PNG_SETJMP_SUPPORTED
|
||||
bool setjmp_wrapper(png_structp png) {
|
||||
return setjmp(png_jmpbuf(png));
|
||||
}
|
||||
#endif
|
||||
|
||||
static cairo_status_t canvas_write_png(cairo_surface_t *surface, png_rw_ptr write_func, canvas_png_write_closure_t *closure) {
|
||||
unsigned int i;
|
||||
cairo_status_t status = CAIRO_STATUS_SUCCESS;
|
||||
uint8_t *data;
|
||||
png_structp png;
|
||||
png_infop info;
|
||||
png_bytep *volatile rows = NULL;
|
||||
png_color_16 white;
|
||||
int png_color_type;
|
||||
int bpc;
|
||||
unsigned int width = cairo_image_surface_get_width(surface);
|
||||
unsigned int height = cairo_image_surface_get_height(surface);
|
||||
|
||||
data = cairo_image_surface_get_data(surface);
|
||||
if (data == NULL) {
|
||||
status = CAIRO_STATUS_SURFACE_TYPE_MISMATCH;
|
||||
return status;
|
||||
}
|
||||
cairo_surface_flush(surface);
|
||||
|
||||
if (width == 0 || height == 0) {
|
||||
status = CAIRO_STATUS_WRITE_ERROR;
|
||||
return status;
|
||||
}
|
||||
|
||||
rows = (png_bytep *) malloc(height * sizeof (png_byte*));
|
||||
if (unlikely(rows == NULL)) {
|
||||
status = CAIRO_STATUS_NO_MEMORY;
|
||||
return status;
|
||||
}
|
||||
|
||||
int stride = cairo_image_surface_get_stride(surface);
|
||||
for (i = 0; i < height; i++) {
|
||||
rows[i] = (png_byte *) data + i * stride;
|
||||
}
|
||||
|
||||
#ifdef PNG_USER_MEM_SUPPORTED
|
||||
png = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL, NULL, NULL, NULL);
|
||||
#else
|
||||
png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
|
||||
#endif
|
||||
|
||||
if (unlikely(png == NULL)) {
|
||||
status = CAIRO_STATUS_NO_MEMORY;
|
||||
free(rows);
|
||||
return status;
|
||||
}
|
||||
|
||||
info = png_create_info_struct (png);
|
||||
if (unlikely(info == NULL)) {
|
||||
status = CAIRO_STATUS_NO_MEMORY;
|
||||
png_destroy_write_struct(&png, &info);
|
||||
free(rows);
|
||||
return status;
|
||||
|
||||
}
|
||||
|
||||
#ifdef PNG_SETJMP_SUPPORTED
|
||||
if (setjmp_wrapper(png)) {
|
||||
png_destroy_write_struct(&png, &info);
|
||||
free(rows);
|
||||
return status;
|
||||
}
|
||||
#endif
|
||||
|
||||
png_set_write_fn(png, closure, write_func, canvas_png_flush);
|
||||
png_set_compression_level(png, closure->closure->compressionLevel);
|
||||
png_set_filter(png, 0, closure->closure->filters);
|
||||
if (closure->closure->resolution != 0) {
|
||||
uint32_t res = static_cast<uint32_t>(round(static_cast<double>(closure->closure->resolution) * 39.3701));
|
||||
png_set_pHYs(png, info, res, res, PNG_RESOLUTION_METER);
|
||||
}
|
||||
|
||||
cairo_format_t format = cairo_image_surface_get_format(surface);
|
||||
|
||||
switch (format) {
|
||||
case CAIRO_FORMAT_ARGB32:
|
||||
bpc = 8;
|
||||
png_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
|
||||
break;
|
||||
#ifdef CAIRO_FORMAT_RGB30
|
||||
case CAIRO_FORMAT_RGB30:
|
||||
bpc = 10;
|
||||
png_color_type = PNG_COLOR_TYPE_RGB;
|
||||
break;
|
||||
#endif
|
||||
case CAIRO_FORMAT_RGB24:
|
||||
bpc = 8;
|
||||
png_color_type = PNG_COLOR_TYPE_RGB;
|
||||
break;
|
||||
case CAIRO_FORMAT_A8:
|
||||
bpc = 8;
|
||||
png_color_type = PNG_COLOR_TYPE_GRAY;
|
||||
break;
|
||||
case CAIRO_FORMAT_A1:
|
||||
bpc = 1;
|
||||
png_color_type = PNG_COLOR_TYPE_GRAY;
|
||||
#ifndef WORDS_BIGENDIAN
|
||||
png_set_packswap(png);
|
||||
#endif
|
||||
break;
|
||||
case CAIRO_FORMAT_RGB16_565:
|
||||
bpc = 8; // 565 gets upconverted to 888
|
||||
png_color_type = PNG_COLOR_TYPE_RGB;
|
||||
break;
|
||||
case CAIRO_FORMAT_INVALID:
|
||||
default:
|
||||
status = CAIRO_STATUS_INVALID_FORMAT;
|
||||
png_destroy_write_struct(&png, &info);
|
||||
free(rows);
|
||||
return status;
|
||||
}
|
||||
|
||||
if ((format == CAIRO_FORMAT_A8 || format == CAIRO_FORMAT_A1) &&
|
||||
closure->closure->palette != NULL) {
|
||||
png_color_type = PNG_COLOR_TYPE_PALETTE;
|
||||
}
|
||||
|
||||
png_set_IHDR(png, info, width, height, bpc, png_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
|
||||
|
||||
if (png_color_type == PNG_COLOR_TYPE_PALETTE) {
|
||||
size_t nColors = closure->closure->nPaletteColors;
|
||||
uint8_t* colors = closure->closure->palette;
|
||||
uint8_t backgroundIndex = closure->closure->backgroundIndex;
|
||||
png_colorp pngPalette = (png_colorp)png_malloc(png, nColors * sizeof(png_colorp));
|
||||
png_bytep transparency = (png_bytep)png_malloc(png, nColors * sizeof(png_bytep));
|
||||
for (i = 0; i < nColors; i++) {
|
||||
pngPalette[i].red = colors[4 * i];
|
||||
pngPalette[i].green = colors[4 * i + 1];
|
||||
pngPalette[i].blue = colors[4 * i + 2];
|
||||
transparency[i] = colors[4 * i + 3];
|
||||
}
|
||||
png_set_PLTE(png, info, pngPalette, nColors);
|
||||
png_set_tRNS(png, info, transparency, nColors, NULL);
|
||||
png_set_packing(png); // pack pixels
|
||||
// have libpng free palette and trans:
|
||||
png_data_freer(png, info, PNG_DESTROY_WILL_FREE_DATA, PNG_FREE_PLTE | PNG_FREE_TRNS);
|
||||
png_color_16 bkg;
|
||||
bkg.index = backgroundIndex;
|
||||
png_set_bKGD(png, info, &bkg);
|
||||
}
|
||||
|
||||
if (png_color_type != PNG_COLOR_TYPE_PALETTE) {
|
||||
white.gray = (1 << bpc) - 1;
|
||||
white.red = white.blue = white.green = white.gray;
|
||||
png_set_bKGD(png, info, &white);
|
||||
}
|
||||
|
||||
/* We have to call png_write_info() before setting up the write
|
||||
* transformation, since it stores data internally in 'png'
|
||||
* that is needed for the write transformation functions to work.
|
||||
*/
|
||||
png_write_info(png, info);
|
||||
if (png_color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
|
||||
png_set_write_user_transform_fn(png, canvas_unpremultiply_data);
|
||||
} else if (format == CAIRO_FORMAT_RGB16_565) {
|
||||
png_set_write_user_transform_fn(png, canvas_convert_565_to_888);
|
||||
} else if (png_color_type == PNG_COLOR_TYPE_RGB) {
|
||||
png_set_write_user_transform_fn(png, canvas_convert_data_to_bytes);
|
||||
png_set_filler(png, 0, PNG_FILLER_AFTER);
|
||||
}
|
||||
|
||||
png_write_image(png, rows);
|
||||
png_write_end(png, info);
|
||||
|
||||
png_destroy_write_struct(&png, &info);
|
||||
free(rows);
|
||||
return status;
|
||||
}
|
||||
|
||||
static void canvas_stream_write_func(png_structp png, png_bytep data, png_size_t size) {
|
||||
cairo_status_t status;
|
||||
struct canvas_png_write_closure_t *png_closure;
|
||||
|
||||
png_closure = (struct canvas_png_write_closure_t *) png_get_io_ptr(png);
|
||||
status = png_closure->write_func(png_closure->closure, data, size);
|
||||
if (unlikely(status)) {
|
||||
cairo_status_t *error = (cairo_status_t *) png_get_error_ptr(png);
|
||||
if (*error == CAIRO_STATUS_SUCCESS) {
|
||||
*error = status;
|
||||
}
|
||||
png_error(png, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
static cairo_status_t canvas_write_to_png_stream(cairo_surface_t *surface, cairo_write_func_t write_func, PngClosure* closure) {
|
||||
struct canvas_png_write_closure_t png_closure;
|
||||
|
||||
if (cairo_surface_status(surface)) {
|
||||
return cairo_surface_status(surface);
|
||||
}
|
||||
|
||||
png_closure.write_func = write_func;
|
||||
png_closure.closure = closure;
|
||||
|
||||
return canvas_write_png(surface, canvas_stream_write_func, &png_closure);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user