diff --git a/frontend/src/footer/PixelSelector.js b/frontend/src/footer/PixelSelector.js index 5f58e8f4..901ac8f0 100644 --- a/frontend/src/footer/PixelSelector.js +++ b/frontend/src/footer/PixelSelector.js @@ -56,8 +56,12 @@ const PixelSelector = (props) => { const availableCount = props.availablePixels - props.availablePixelsUsed; if (props.availablePixels == 0) return; - const templateX = props.overlayTemplate.position % props.width; - const templateY = Math.floor(props.overlayTemplate.position / props.width); + // Use correct canvas dimensions + const canvasWidth = 518; + const canvasHeight = 396; + + const templateX = props.overlayTemplate.position % canvasWidth; + const templateY = Math.floor(props.overlayTemplate.position / canvasWidth); const canvas = props.canvasRef.current; const context = canvas.getContext('2d'); @@ -72,6 +76,16 @@ const PixelSelector = (props) => { const canvasX = templateX + pixelX; const canvasY = templateY + pixelY; + // Validate pixel is within canvas bounds + if ( + canvasX < 0 || + canvasX >= canvasWidth || + canvasY < 0 || + canvasY >= canvasHeight + ) { + continue; + } + // Get current pixel color const imageData = context.getImageData(canvasX, canvasY, 1, 1).data; const currentColor = `${imageData[0] @@ -90,7 +104,10 @@ const PixelSelector = (props) => { } } - while (pixelsToPlace.length < availableCount) { + // Ensure we don't exceed available pixels + const pixelsNeeded = Math.min(availableCount, pixelsToPlace.length); + + while (pixelsToPlace.length < pixelsNeeded) { // Place random pixel in template let idx = Math.floor( Math.random() * props.templatePixels.pixelData.length @@ -99,8 +116,20 @@ const PixelSelector = (props) => { const randomY = Math.floor(idx / props.templatePixels.width); const colorId = props.templatePixels.pixelData[idx]; if (colorId === 0xff) continue; // Skip transparent pixels + const canvasX = templateX + randomX; const canvasY = templateY + randomY; + + // Validate pixel is within canvas bounds + if ( + canvasX < 0 || + canvasX >= canvasWidth || + canvasY < 0 || + canvasY >= canvasHeight + ) { + continue; + } + pixelsToPlace.push({ x: canvasX, y: canvasY, @@ -110,7 +139,7 @@ const PixelSelector = (props) => { // Randomly select pixels up to available amount const shuffledPixels = pixelsToPlace.sort(() => Math.random() - 0.5); - const selectedPixels = shuffledPixels.slice(0, availableCount); + const selectedPixels = shuffledPixels.slice(0, pixelsNeeded); await props.addExtraPixels(selectedPixels); };