Skip to content

Commit

Permalink
Add opacity option (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanterdro authored and lukechilds committed Feb 14, 2018
1 parent 3f52a84 commit b52d112
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,22 @@ Using the same source images as above would output this:

<img src="/test/fixtures/face-custom-positions.png" width="128">

### Opacity

The opacity can also be tweaked on each image.

```js
mergeImages([
{ src: 'body.png' },
{ src: 'eyes.png', opacity: 0.7 },
{ src: 'mouth.png', opacity: 0.3 }
])
.then(b64 => ...);
// data:image/png;base64,iVBORw0KGgoAA...
```

<img src="/test/fixtures/face-opacity.png" width="128">

### Dimensions

By default the new image dimensions will be set to the width of the widest source image and the height of the tallest source image. You can manually specify your own dimensions in the options object:
Expand Down
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ const mergeImages = (sources = [], options = {}) => new Promise(resolve => {
canvas.height = getSize('height');

// Draw images to canvas
images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0));
images.forEach(image => {
ctx.globalAlpha = image.opacity ? image.opacity : 1;
return ctx.drawImage(image.img, image.x || 0, image.y || 0);
});

if (options.Canvas && options.format === 'image/jpeg') {
// Resolve data URI for node-canvas jpeg async
Expand Down
Binary file added test/fixtures/face-opacity.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,20 @@ test('mergeImages uses custom jpeg quality', async t => {

t.true(b64 === expectedB64);
});

test('mergeImages uses opacity', async t => {
t.plan(1);
const images = await Promise.all([
{ src: 'body.png' },
{ src: 'eyes.png', opacity: 0.7 },
{ src: 'mouth.png', opacity: 0.3 }
].map(image => fixtures.getImage(image.src).then(src => {
image.src = src;
return image;
})));
const b64 = await mergeImages(images, { Canvas });

const expectedB64 = await fixtures.getDataURI('face-opacity.png');

t.true(b64 === expectedB64);
});

0 comments on commit b52d112

Please sign in to comment.