Skip to content

Instantly share code, notes, and snippets.

@colinkiama
Last active May 6, 2023 14:28
Show Gist options
  • Save colinkiama/60396d782520ee3ba8e21479bdb31224 to your computer and use it in GitHub Desktop.
Save colinkiama/60396d782520ee3ba8e21479bdb31224 to your computer and use it in GitHub Desktop.
Useful code for drawing front-end of four-in-a-row game with HTML5 Canvas API
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Tutorial</title>
<script>
function draw() {
const canvas = document.getElementById("tutorial");
if (canvas.getContext) {
const ctx = canvas.getContext("2d");
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
ctx.strokeStyle = `rgb(0, ${Math.floor(255 - 42.5 * i)}, ${Math.floor(255 - 42.5 * j)})`;
ctx.beginPath();
ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, 2 * Math.PI, true);
ctx.stroke();
}
}
}
}
</script>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body onload="draw();">
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
window.addEventListener('load', (e) => draw());
function draw() {
const ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 30, 0, Math.PI * 2, true);
ctx.arc(50, 50, 15, 0, Math.PI * 2, true);
ctx.fill("evenodd");
}
// Get the DPR and size of the canvas
const dpr = window.devicePixelRatio;
const rect = canvas.getBoundingClientRect();
// Set the "actual" size of the canvas
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Scale the context to ensure correct drawing operations
ctx.scale(dpr, dpr);
// Set the "drawn" size of the canvas
canvas.style.width = `${rect.width}px`;
canvas.style.height = `${rect.height}px`;
const scaleX = window.innerWidth / canvas.width;
const scaleY = window.innerHeight / canvas.height;
const scaleToFit = Math.min(scaleX, scaleY);
const scaleToCover = Math.max(scaleX, scaleY);
stage.style.transformOrigin = "0 0"; //scale from top left
stage.style.transform = `scale(${scaleToFit})`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment