Skip to content

Commit

Permalink
defend pixel placement fix
Browse files Browse the repository at this point in the history
  • Loading branch information
supreme2580 committed Dec 16, 2024
1 parent b334578 commit 7cf2aa3
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions frontend/src/footer/PixelSelector.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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]
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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);
};
Expand Down

0 comments on commit 7cf2aa3

Please sign in to comment.