MrThoe

codhe

Feb 24th, 2023
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. // Constants for the image
  2. var IMAGE_URL = "https://codehs.com/static/img/zebra.jpg";
  3. var IMAGE_WIDTH = 350;
  4. var IMAGE_HEIGHT = 250;
  5. var IMAGE_X = getWidth() / 2 - IMAGE_WIDTH / 2;
  6. var IMAGE_Y = getHeight() / 2 - IMAGE_HEIGHT / 2;
  7.  
  8. // Constants for the pixel array
  9. var RED = 0;
  10. var GREEN = 1;
  11. var BLUE = 2;
  12.  
  13. // Constants for the pixel filter
  14. var MAX_COLOR_VALUE = 255;
  15.  
  16. // We need to wait for the image to load before modifying it
  17. var IMAGE_LOAD_WAIT_TIME = 50;
  18.  
  19. // Inverts the colors of each pixel in the WebImage image
  20. function invert(image) {
  21. for(var x = 0; x < image.getWidth(); x++) {
  22. for (var y = 0; y < image.getHeight(); y++) {
  23. // Get the current pixel
  24. var pixel = image.getPixel(x, y);
  25.  
  26. // Modify the current pixel
  27. pixel = invertPixel(pixel);
  28.  
  29. // Update the image with the modified pixel
  30. image.setRed(x, y, pixel[RED]);
  31. image.setGreen(x, y, pixel[GREEN]);
  32. image.setBlue(x, y, pixel[BLUE]);
  33. }
  34. }
  35. }
  36.  
  37. // Given a pixel array with 3 values [R, G, B]
  38. // Modifies the pixel array such that each value is inverted ie:
  39. // R = 255 - R
  40. // G = 255 - G
  41. // B = 255 - B
  42. // Returns the modified pixel array
  43. function invertPixel(pixel) {
  44. // Get the RGB values from this pixel array
  45. var red = pixel[RED];
  46. var green = pixel[GREEN];
  47. var blue = pixel[BLUE];
  48.  
  49. // Modify the pixel array so that each value is inverted
  50. pixel[RED] = MAX_COLOR_VALUE - red;
  51. pixel[GREEN] = MAX_COLOR_VALUE - green;
  52. pixel[BLUE] = MAX_COLOR_VALUE - blue;
  53.  
  54. // Return the modified pixel array
  55. return pixel;
  56. }
  57.  
  58. function start() {
  59. // Set up the image
  60. var image = new WebImage(IMAGE_URL);
  61. image.setSize(IMAGE_WIDTH, IMAGE_HEIGHT);
  62. image.setPosition(IMAGE_X, IMAGE_Y);
  63.  
  64. // Add it to the canvas
  65. add(image);
  66.  
  67. // Wait for it to load before applying the filter
  68. setTimeout(function(){
  69. invert(image);
  70. }, IMAGE_LOAD_WAIT_TIME);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment