Pixels in a p5js canvas can be accessed directly as a 1D array. Just like the screen buffer on a GBA. Although 2D array can definitely make understanding this sketch way easier, it is what it is.
The following demonstrates a simple drawing program that paints in green when dragging with left mouse cursor and erase when dragging with right cursor key.
const bs = 5; //brush size
const bse = 20;//eraser size
function setup() {
pixelDensity(2);
createCanvas(400, 400);
background(230);
for (let element of document.getElementsByClassName("p5Canvas")) {
element.addEventListener("contextmenu", (e) => e.preventDefault());
}
}
function draw() {
if (mouseIsPressed) {
if(mouseButton === LEFT){
applyPixel(mouseX, mouseY, createVector(0,255,0), bs);
}
if(mouseButton === RIGHT){
applyPixel(mouseX, mouseY, createVector(230,230,230), bse);
}
}
}
function applyPixel(x, y, colour, brushSize) {
loadPixels();
x *= 2; // Adjust for pixel density
y *= 2; // Adjust for pixel density
for (let i = -brushSize; i < brushSize; i++) {
for (let j = -brushSize; j < brushSize; j++) {
let pixelX = x + i;
let pixelY = y + j;
if (pixelX >= 0 && pixelX < width * 2 && pixelY >= 0 && pixelY < height * 2) {
let index = (pixelX + pixelY * width * 2) * 4;
pixels[index] = colour.x;
pixels[index + 1] = colour.y;
pixels[index + 2] = colour.z;
pixels[index + 3] = 255;
}
}
}
updatePixels();
}
function mouseWheel(event) {
return false;
}
Code language: JavaScript (javascript)
Leave a Reply