getImagePixels.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import defined from "./defined.js";
  2. const context2DsByWidthAndHeight = {};
  3. /**
  4. * Extract a pixel array from a loaded image. Draws the image
  5. * into a canvas so it can read the pixels back.
  6. *
  7. * @function getImagePixels
  8. *
  9. * @param {HTMLImageElement|ImageBitmap} image The image to extract pixels from.
  10. * @param {Number} width The width of the image. If not defined, then image.width is assigned.
  11. * @param {Number} height The height of the image. If not defined, then image.height is assigned.
  12. * @returns {ImageData} The pixels of the image.
  13. */
  14. function getImagePixels(image, width, height) {
  15. if (!defined(width)) {
  16. width = image.width;
  17. }
  18. if (!defined(height)) {
  19. height = image.height;
  20. }
  21. let context2DsByHeight = context2DsByWidthAndHeight[width];
  22. if (!defined(context2DsByHeight)) {
  23. context2DsByHeight = {};
  24. context2DsByWidthAndHeight[width] = context2DsByHeight;
  25. }
  26. let context2d = context2DsByHeight[height];
  27. if (!defined(context2d)) {
  28. const canvas = document.createElement("canvas");
  29. canvas.width = width;
  30. canvas.height = height;
  31. context2d = canvas.getContext("2d");
  32. context2d.globalCompositeOperation = "copy";
  33. context2DsByHeight[height] = context2d;
  34. }
  35. context2d.drawImage(image, 0, 0, width, height);
  36. return context2d.getImageData(0, 0, width, height).data;
  37. }
  38. export default getImagePixels;