index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { isNodePattern, throwError } from '@jimp/utils';
  2. /**
  3. * Displaces the image based on the provided displacement map
  4. * @param {object} map the source Jimp instance
  5. * @param {number} offset the maximum displacement value
  6. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  7. * @returns {Jimp} this for chaining of methods
  8. */
  9. export default () => ({
  10. displace(map, offset, cb) {
  11. if (typeof map !== 'object' || map.constructor !== this.constructor) {
  12. return throwError.call(this, 'The source must be a Jimp image', cb);
  13. }
  14. if (typeof offset !== 'number') {
  15. return throwError.call(this, 'factor must be a number', cb);
  16. }
  17. const source = this.cloneQuiet();
  18. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
  19. x,
  20. y,
  21. idx
  22. ) {
  23. let displacement = (map.bitmap.data[idx] / 256) * offset;
  24. displacement = Math.round(displacement);
  25. const ids = this.getPixelIndex(x + displacement, y);
  26. this.bitmap.data[ids] = source.bitmap.data[idx];
  27. this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];
  28. this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];
  29. });
  30. if (isNodePattern(cb)) {
  31. cb.call(this, null, this);
  32. }
  33. return this;
  34. }
  35. });