spriteProcessor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. class SpriteProcessor {
  2. constructor() {
  3. this.processedSprites = new Map();
  4. }
  5. processSpriteSheet(originalImage, keyColor = '#00ffff') {
  6. const canvas = document.createElement('canvas');
  7. const ctx = canvas.getContext('2d');
  8. canvas.width = originalImage.width;
  9. canvas.height = originalImage.height;
  10. // Draw original image
  11. ctx.drawImage(originalImage, 0, 0);
  12. // Get image data
  13. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  14. const data = imageData.data;
  15. // Convert key colors to RGB
  16. const keyR = parseInt(keyColor.slice(1, 3), 16);
  17. const keyG = parseInt(keyColor.slice(3, 5), 16);
  18. const keyB = parseInt(keyColor.slice(5, 7), 16);
  19. // Convert spritesheet background color to RGB
  20. const bgColor = '#a0a7ca';
  21. const bgR = parseInt(bgColor.slice(1, 3), 16);
  22. const bgG = parseInt(bgColor.slice(3, 5), 16);
  23. const bgB = parseInt(bgColor.slice(5, 7), 16);
  24. // Make key colors transparent
  25. for (let i = 0; i < data.length; i += 4) {
  26. const r = data[i];
  27. const g = data[i + 1];
  28. const b = data[i + 2];
  29. // Check if pixel matches key color (with small tolerance)
  30. if (Math.abs(r - keyR) < 10 && Math.abs(g - keyG) < 10 && Math.abs(b - keyB) < 10) {
  31. data[i + 3] = 0; // Set alpha to 0 (transparent)
  32. }
  33. // Check if pixel matches spritesheet background color (with small tolerance)
  34. else if (Math.abs(r - bgR) < 10 && Math.abs(g - bgG) < 10 && Math.abs(b - bgB) < 10) {
  35. data[i + 3] = 0; // Set alpha to 0 (transparent)
  36. }
  37. }
  38. // Put processed image back
  39. ctx.putImageData(imageData, 0, 0);
  40. // Create new image with transparency
  41. const processedImage = new Image();
  42. processedImage.src = canvas.toDataURL('image/png');
  43. return processedImage;
  44. }
  45. }
  46. // Export for use in game
  47. window.SpriteProcessor = SpriteProcessor;