
랜덤 색상의 네모를 그리는 간단한 Canvas 예제 입니다. Start 버튼을 누르면 그리기가 시작되고, 다시 누르면 그림이 갱신됩니다.
<!DOCTYPE html>
<style>
#myCanvas {
border: 2px solid lightgray;
max-width: 100%;
box-sizing: border-box;
}
#myBtn { padding: 3px 10px; }
</style>
<p><button id="myBtn" onclick="start()">Start</button></p>
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
const ROWS = 7;
const COLS = 7;
const GAP = 10;
const WIDTH = (canvas.width - (GAP * (COLS + 1))) / COLS;
const HEIGHT = (canvas.height - (GAP * (ROWS + 1))) / ROWS;
var colorMaker = {
reset: function() {
this.values = [
randInt(1, 3), randInt(1, 3), randInt(1, 3)
];
},
getColor: function() {
var rgb = this.values.map(
n => randInt(30 * (n - 1), 30 * n) + 160);
return "rgb(" + rgb.join(",") + ")";
}
};
var count = 0;
var timer = null;
function start() {
if (timer) clearInterval(timer);
clearCanvas();
count = 0;
colorMaker.reset();
timer = setInterval(drawColorRect, 100);
}
function clearCanvas() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawColorRect() {
if (count >= ROWS * COLS) return;
var x = GAP + (WIDTH + GAP) * (count % COLS);
var y = GAP + (HEIGHT + GAP) * Math.floor(count / COLS);
ctx.fillStyle = colorMaker.getColor();
ctx.fillRect(x, y, WIDTH, HEIGHT);
count++;
}
function randInt(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
</script>