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.
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.
<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; | |
} |