index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { isNodePattern } from '@jimp/utils';
  2. /**
  3. * Creates a circle out of an image.
  4. * @param {function(Error, Jimp)} options (optional)
  5. * opacity - opacity of the shadow between 0 and 1
  6. * size,- of the shadow
  7. * blur - how blurry the shadow is
  8. * x- x position of shadow
  9. * y - y position of shadow
  10. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  11. * @returns {Jimp} this for chaining of methods
  12. */
  13. export default () => ({
  14. shadow(options = {}, cb) {
  15. if (typeof options === 'function') {
  16. cb = options;
  17. options = {};
  18. }
  19. const { opacity = 0.7, size = 1.1, x = -25, y = 25, blur = 5 } = options;
  20. // clone the image
  21. const orig = this.clone();
  22. const shadow = this.clone();
  23. // turn all it's pixels black
  24. shadow.scan(
  25. 0,
  26. 0,
  27. shadow.bitmap.width,
  28. shadow.bitmap.height,
  29. (x, y, idx) => {
  30. shadow.bitmap.data[idx] = 0x00;
  31. shadow.bitmap.data[idx + 1] = 0x00;
  32. shadow.bitmap.data[idx + 2] = 0x00;
  33. // up the opacity a little,
  34. shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(
  35. shadow.bitmap.data[idx + 3] * opacity
  36. );
  37. this.bitmap.data[idx] = 0x00;
  38. this.bitmap.data[idx + 1] = 0x00;
  39. this.bitmap.data[idx + 2] = 0x00;
  40. this.bitmap.data[idx + 3] = 0x00;
  41. }
  42. );
  43. // enlarge it. This creates a "shadow".
  44. shadow
  45. .resize(shadow.bitmap.width * size, shadow.bitmap.height * size)
  46. .blur(blur);
  47. // Then blit the "shadow" onto the background and the image on top of that.
  48. this.composite(shadow, x, y);
  49. this.composite(orig, 0, 0);
  50. if (isNodePattern(cb)) {
  51. cb.call(this, null, this);
  52. }
  53. return this;
  54. }
  55. });