getImagePixels.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // Since we re-use contexts, use the willReadFrequently option – See https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-will-read-frequently
  32. context2d = canvas.getContext("2d", { willReadFrequently: true });
  33. context2d.globalCompositeOperation = "copy";
  34. context2DsByHeight[height] = context2d;
  35. }
  36. context2d.drawImage(image, 0, 0, width, height);
  37. return context2d.getImageData(0, 0, width, height).data;
  38. }
  39. export default getImagePixels;