Path: blob/master/node_modules/@jimp/plugin-mask/src/index.js
1126 views
import { isNodePattern, throwError } from '@jimp/utils';12/**3* Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent.4* @param {Jimp} src the source Jimp instance5* @param {number} x the horizontal position to blit the image6* @param {number} y the vertical position to blit the image7* @param {function(Error, Jimp)} cb (optional) a callback for when complete8* @returns {Jimp} this for chaining of methods9*/10export default () => ({11mask(src, x = 0, y = 0, cb) {12if (!(src instanceof this.constructor)) {13return throwError.call(this, 'The source must be a Jimp image', cb);14}1516if (typeof x !== 'number' || typeof y !== 'number') {17return throwError.call(this, 'x and y must be numbers', cb);18}1920// round input21x = Math.round(x);22y = Math.round(y);2324const w = this.bitmap.width;25const h = this.bitmap.height;26const baseImage = this;2728src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function(29sx,30sy,31idx32) {33const destX = x + sx;34const destY = y + sy;3536if (destX >= 0 && destY >= 0 && destX < w && destY < h) {37const dstIdx = baseImage.getPixelIndex(destX, destY);38const { data } = this.bitmap;39const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;4041baseImage.bitmap.data[dstIdx + 3] *= avg / 255;42}43});4445if (isNodePattern(cb)) {46cb.call(this, null, this);47}4849return this;50}51});525354