Skip to content

Instantly share code, notes, and snippets.

@scottymeyers
Created October 19, 2020 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottymeyers/806f7250902725b0dcaeae242055d56e to your computer and use it in GitHub Desktop.
Save scottymeyers/806f7250902725b0dcaeae242055d56e to your computer and use it in GitHub Desktop.
Canvas Percent Coverage Visual

Canvas Percent Coverage Visual

Divvy's up the HTML Canvas into equally sized squares and draws color onto a specified percentage of them.

A Pen by Scott Meyers on CodePen.

License.

<canvas height="320" width="720" />
const color = '#d9ce6c';
const percentage = 80;
const squareSize = 4;
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const canvasHeight = canvas.height;
const canvasWidth = canvas.width;
const columns = canvasWidth / squareSize;
const squares = [];
const totalSquares = columns * (canvasHeight / squareSize);
Array.from({ length: totalSquares }, (x, i) => {
const position = {
y: Math.trunc(i / (canvasWidth / squareSize)) * squareSize,
x: i * squareSize - Math.trunc((i * squareSize) / canvasWidth) * canvasWidth,
};
return squares.push(position);
});
const randomizedPercentageOfSquares = squares.sort(() => Math.random() - 0.5);
randomizedPercentageOfSquares
.slice(0, totalSquares * (percentage / 100))
.map((square) => {
ctx.fillStyle = color;
return ctx.fillRect(square.x, square.y, squareSize, squareSize);
});
body {
background: whitesmoke;
}
canvas {
background: blue;
bottom: 0;
display: block;
left: 0;
margin: auto;
padding: 6px;
position: fixed;
right: 0;
top: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment