index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { isNodePattern } from '@jimp/utils';
  2. /**
  3. * Creates a circle out of an image.
  4. * @param {function(Error, Jimp)} options (optional) radius, x, y
  5. * @param {function(Error, Jimp)} cb (optional) a callback for when complete
  6. * @returns {Jimp} this for chaining of methods
  7. */
  8. export default () => ({
  9. circle(options = {}, cb) {
  10. if (typeof options === 'function') {
  11. cb = options;
  12. options = {};
  13. }
  14. const radius =
  15. options.radius ||
  16. (this.bitmap.width > this.bitmap.height
  17. ? this.bitmap.height
  18. : this.bitmap.width) / 2;
  19. const center = {
  20. x: typeof options.x === 'number' ? options.x : this.bitmap.width / 2,
  21. y: typeof options.y === 'number' ? options.y : this.bitmap.height / 2
  22. };
  23. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
  24. x,
  25. y,
  26. idx
  27. ) {
  28. const curR = Math.sqrt(
  29. Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2)
  30. );
  31. if (radius - curR <= 0.0) {
  32. this.bitmap.data[idx + 3] = 0;
  33. } else if (radius - curR < 1.0) {
  34. this.bitmap.data[idx + 3] = 255 * (radius - curR);
  35. }
  36. });
  37. if (isNodePattern(cb)) {
  38. cb.call(this, null, this);
  39. }
  40. return this;
  41. }
  42. });