Skip to content

Instantly share code, notes, and snippets.

@ahmtcn123
Last active June 26, 2024 14:53
Show Gist options
  • Save ahmtcn123/354ba783f2b44e7e862f6345426a45bc to your computer and use it in GitHub Desktop.
Save ahmtcn123/354ba783f2b44e7e862f6345426a45bc to your computer and use it in GitHub Desktop.
A Pixel density scaleable framebuffer implementation in js canvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<style>
#myCanvas {
border: 2px solid red;
}
</style>
<h1>JS Canvas Pixel Buffer</h1>
<canvas id="myCanvas" height="500px" width="500px">
Your browser does not support the HTML5 canvas tag.
</canvas>
<br />
<label for="myRange">Pixel Density</label>
<input type="range" min="1" max="50" value="50" id="myRange" />
<br />
<label for="height">Height</label>
<input type="range" min="32" max="1024" value="500" id="height" />
<br />
<label for="width">Width</label>
<input type="range" min="32" max="1024" value="500" id="width" />
</body>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let canvas_width = 500;
let canvas_height = 500;
canvas.height = canvas_height;
canvas.width = canvas_width;
function main() {
let pixelDensity = 5;
let frameBuffer = [];
let pixel_width = canvas_width / pixelDensity;
let pixel_height = canvas_height / pixelDensity;
function renderer() {
pixel_width = canvas_width / pixelDensity;
pixel_height = canvas_height / pixelDensity;
// Clear the canvas before drawing
ctx.clearRect(0, 0, canvas_height, canvas_width);
for (let i = 0; i < frameBuffer.length; i++) {
const rgb = frameBuffer[i];
const y = i == 0 ? 0 : Math.floor(i / pixel_width);
const x = Math.floor(i % pixel_width);
ctx.fillStyle = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
ctx.fillRect(
x == 0 ? 0 : x * pixelDensity,
y == 0 ? 0 : y * pixelDensity,
pixelDensity,
pixelDensity
);
}
requestAnimationFrame(renderer);
}
setInterval(() => {
if (frameBuffer.length >= pixel_width * pixel_height) {
frameBuffer = [];
ctx.clearRect(0, 0, width, height);
}
frameBuffer.push([
Math.floor(Math.random() * 255),
Math.floor(Math.random() * 255),
Math.floor(Math.random() * 255),
]);
}, 5);
renderer();
requestAnimationFrame(renderer);
document.getElementById("myRange").oninput = (e) => {
pixelDensity = Number(e.target.value);
};
document.getElementById("height").oninput = (e) => {
height = Number(e.target.value);
canvas.height = height;
canvas_height = height;
};
document.getElementById("width").oninput = (e) => {
width = Number(e.target.value);
canvas.width = width;
canvas_width = width;
};
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment