Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created June 13, 2019 11:41
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 Garciat/494719f903661f2348fe3bce1923c874 to your computer and use it in GitHub Desktop.
Save Garciat/494719f903661f2348fe3bce1923c874 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
height: 100%;
margin: 0;
}
</style>
<script>
function main() {
let screenW = document.body.clientWidth;
let screenH = document.body.clientHeight;
console.log(screenW, screenH);
let canvas = document.createElement('canvas');
canvas.width = screenW;
canvas.height = screenH;
document.body.appendChild(canvas);
let ctx = canvas.getContext('2d');
let rectRatio = 4;
let rectW = 40;
let rectH = rectW * rectRatio;
let colors = ['hsl(0, 0%, 15%)', 'hsl(0, 0%, 30%)', 'hsl(0, 0%, 50%)'];
let chosen = [];
function chooseColor() {
while (true) {
let color = arrayChoice(colors);
if (chosen[0] === color) {
if (chosen.length === 2) {
continue;
} else {
chosen.unshift(color);
}
} else {
chosen = [color];
}
return color;
}
}
// draw1(ctx, rectW, rectH, chooseColor);
draw2(ctx, rectW, rectH, chooseColor);
}
function draw2(ctx, rectW, rectH, colorF) {
ctx.translate(0, -rectH);
for (let i = 0; i < 40; ++i) {
for (let j = 0; j < 40; ++j) {
ctx.save();
ctx.translate(Math.floor(i/2) * hyp(rectH, rectH), j * hyp(rectW, rectW));
ctx.rotate(Math.PI / 4 * Math.pow(-1, i + 1));
ctx.fillStyle = colorF();
ctx.fillRect(0, 0, rectW, rectH);
ctx.restore();
}
}
}
function draw1(ctx, rectW, rectH, colorF) {
ctx.save();
ctx.rotate(Math.PI / 4);
ctx.translate(-rectH, -rectH);
for (let i = 0; i < 40; ++i) {
let x = i * rectW;
let y = i * rectW;
for (let j = 0; j < 40; ++j) {
ctx.fillStyle = colorF();
if (j % 2 == 0) {
ctx.fillRect(x, y, rectW, rectH);
y -= rectW;
} else {
ctx.fillRect(x, y, rectH, rectW);
y -= rectH;
x += Math.abs(rectH - rectW);
}
}
}
ctx.restore();
}
function hyp(a, b) {
return Math.sqrt(a * a + b * b);
}
function randomInt(a, b) {
return a + Math.floor((b - a) * Math.random());
}
function arrayChoice(arr) {
return arr[randomInt(0, arr.length)];
}
window.addEventListener('load', main);
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment