xxxxxxxxxx
174
let fColor;
let bColor;
let img;
let imgW = 256;
let imgH = 256;
let zoomLevels =
[
1/8, 1/4, 1/3, 1/2, 1, 3/2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 20, 24, 32,
];
let zoomIndex = zoomLevels.findIndex(item => item === 1);
function setup()
{
createCanvas(windowWidth, windowHeight);
noSmooth();
img = createGraphics(imgW, imgH);
img.noSmooth();
img.background(255);
fColor = color(0);
bColor = color(255);
}
function draw()
{
background(40);
// img.loadPixels();
HandleDrawing();
// img.updatePixels();
DrawImg();
}
function keyPressed()
{
if (keyCode === 187) // = (used for +)
ZoomIn();
else if (keyCode === 189) // -
ZoomOut();
else if (keyCode === 48) // 0
ZoomReset();
}
function HandleDrawing()
{
if (!mouseIsPressed) return;
if (mouseButton === CENTER) return;
let x = GetMouseX();
let px = GetPMouseX();
// if (px === x) return;
let y = GetMouseY();
let py = GetPMouseY();
// if (py === y) return;
let c = mouseButton === LEFT ? fColor : bColor;
Line(px, py, x, y, c);
}
function SetPixel(x, y, c)
{
let i = 4 * (x + imgW * y);
let iR = i + 0;
let iG = i + 1;
let iB = i + 2;
let iA = i + 3;
img.pixels[iR] = red(c);
img.pixels[iG] = green(c);
img.pixels[iB] = blue(c);
img.pixels[iA] = alpha(c);
}
function DrawImg()
{
image(img, 0, 0, img.width * GetZoom(), img.height * GetZoom());
}
function GetMouseX()
{
return ToZoom(mouseX);
}
function GetMouseY()
{
return ToZoom(mouseY);
}
function GetPMouseX()
{
return ToZoom(pmouseX);
}
function GetPMouseY()
{
return ToZoom(pmouseY);
}
function GetZoom()
{
return zoomLevels[zoomIndex];
}
function ZoomIn()
{
zoomIndex = min(zoomIndex + 1, zoomLevels.length - 1);
}
function ZoomOut()
{
zoomIndex = max(zoomIndex - 1, 0);
}
function ZoomReset()
{
zoomIndex = zoomLevels.findIndex(item => item === 1);
}
function Line(x0, y0, x1, y1, c)
{
let dx = x1 - x0;
let dy = y1 - y0;
for (let x = x0; x <= x1; ++x)
{
let f = (x - x0) / dx;
let y = y0 + floor(f * dy);
FillPixel(x, y, c);
}
}
function FillPixel(x, y, c)
{
x += 0.5;
y += 0.5;
img.push();
{
img.stroke(c);
img.strokeWeight(1);
img.point(x, y);
}
img.pop();
}
function ToZoom(n)
{
return floor(n / GetZoom());
}
function FromZoom(n)
{
return n * GetZoom();
}