diff --git a/README.md b/README.md index 5741c0a..31c225e 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@
[![NPM](https://nodei.co/npm/trim-canvas.png?downloads=true&downloadRank=true&stars=true)](https://npmjs.org/package/trim-canvas) -A tiny (< 100 LoC) library for trimming whitespace from a `canvas` element with no dependencies. +A tiny (~100 LoC) library for trimming whitespace from a `canvas` element with no dependencies. ## Installation @@ -35,9 +35,29 @@ trimCanvas(canvas) ``` If you don't want to mess with your existing canvas, then simply clone the canvas element beforehand. +`trim-canvas` v0.2+ has built-in support for cloning: + +```javascript +const newTrimmedCanvas = trimCanvas(canvas, {clone: true}) +``` + +Can view the [full list of options](#API) below. `trim-canvas` returns the canvas element for easy chaining. +### API + +#### `trimCanvas(canvas, options)` + +- arguments + - **canvas** *Canvas object* The canvas to be trimmed. + - **options** *object* Optional arguments. + - **clone** *bool* Whether to clone the canvas before trimming (default: `false`). + - **createCanvas** *function* A custom function to create a Canvas (defaults to DOM implementation). + Supports [`node-canvas`'s `createCanvas`](https://github.com/Automattic/node-canvas#createcanvas). + +- returns the trimmed canvas (original or cloned) + ## Example Can see how `trim-canvas` is used inside of `react-signature-canvas` [here](https://github.com/agilgur5/react-signature-canvas/blob/310bff81813509a4035bedfe50d76e7045a880cb/src/index.js#L53-L64). diff --git a/package.json b/package.json index 8625e51..9aff454 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "trim-canvas", - "version": "0.1.2", + "version": "0.2.0", "description": "A tiny library for trimming whitespace from a canvas element", "main": "build/index.js", "files": [ diff --git a/src/index.js b/src/index.js index ab1fd2d..43dbe55 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,7 @@ -export default function trimCanvas (canvas) { +export default function trimCanvas (canvas, options = {}) { + const {clone} = options + let {createCanvas = createCanvasDOM} = options // support node-canvas, etc + const context = canvas.getContext('2d') const imgWidth = canvas.width @@ -21,6 +24,15 @@ export default function trimCanvas (canvas) { const trimmedData = context.getImageData(cropLeft, cropTop, cropXDiff, cropYDiff) + // early return if cloning + if (clone) { + const copy = createCanvas() + copy.width = cropXDiff + copy.height = cropYDiff + copy.getContext('2d').putImageData(trimmedData, 0, 0) + return copy + } + // set the trimmed width and height canvas.width = cropXDiff canvas.height = cropYDiff @@ -85,3 +97,7 @@ function scanX (fromLeft, imgWidth, imgHeight, imgData) { // the whole image is white already return null } + +function createCanvasDOM () { + return document.createElement('canvas') +}