under-canvas
v0.3.1
Published
Plain sailing image previews, powered by canvas.
Downloads
11
Maintainers
Readme
under-canvas.js
Plain sailing image previews, powered by canvas.
Have you ever wanted to preview an image before it gets uploaded? Or generate a thumbnail of an image on the fly?
Canvas
can be extremely powerful when it comes to manipulating images, but there's a lot of complexity just to perform seemingly easy tasks.
Under Canvas makes it incredibly effortless to generate image previews from a number of different sources.
The function returns a Promise
, which resolves to base64
data URI.
Installation
npm install --save under-canvas
ES6 import
import underCanvas from 'under-canvas';
Alternatively, you can use it directly in the browser:
<script type='http://unpkg.com/under-canvas'></script>
underCanvas
is directly attached to the window:
window.underCanvas()
Usage
External URL
Note that manipulating images from a remote source requires
Access-Control-Allow-Origin
to be set.
underCanvas('http://localhost:8080/image.jpg').then((b64) => {
const img = document.createElement('img');
img.src = b64;
document.getElementById('root').appendChild(img);
})
Base-64 encoded image
underCanvas('data:image/png;base64,...').then((b64) => {
const img = document.createElement('img');
img.src = b64;
document.getElementById('root').appendChild(img);
})
API Usage
underCanvas(image, [options])
Returns a Promise
which resolves a base64
string of the preview.
background
Type: string
Background colour to use if not transparent. Useful when scaling to fit images.
Defaults to
transparent
.
format
Type: string
Default: image/png
Format of the image to export.
Supports a number of different image formats (dependant on browser). eg.
image/jpeg
andimage/png
are supported by all browsers, but Chrome also supportsimage/webp
.
quality
Type: number
Default: 0.9
width
Type: number
Width of the exported image.
Defaults to original size.
height
Type: number
Height of the exported image.
Defaults to original size.
crop
Type: boolean
Default: false
Resizes the image to fill the size and crops excess edges.
By default, the original image will be resized to fit within the specified size, ensuring the image is fully visible and no cropping occurs. If crop is set to
true
, the image will be resized to ensure that the width and height are greater than or equal to the expected size.
Planned features
- Generating previews from
input[type=file]
- Detect browser support for
Canvas
nodeJS
support usingnode-canvas
Contributing
Contributions are certainly welcome. Please take a look at any existing issues.