Skip to content

Instantly share code, notes, and snippets.

@minrenmtv
Last active December 24, 2015 09:58
Show Gist options
  • Save minrenmtv/6780374 to your computer and use it in GitHub Desktop.
Save minrenmtv/6780374 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Canvas Color</title>
<script type="text/javascript">
function Box(id, color) {
this.id = id;
this.color = color;
}
var boxes = [];
var doneBoxes = [];
var pallet = ['red', 'yellow', 'green', 'purple'];
var dimension = 20;
var boxWidth = 20;
var canvasSize = dimension * boxWidth + 100;
var canvas, ctx;
function init() {
canvas = document.getElementById("color");
ctx = canvas.getContext("2d");
var id = 0;
for (var i = 0; i < dimension; i++) {
for (var j = 0; j < dimension; j++) {
var c = getColor();
var b = new Box(id, c);
boxes.push(b);
ctx.fillStyle = c;
var col = to2d(id).col;
var row = to2d(id).row;
var x = col * boxWidth + 100;
var y = row * boxWidth + 100;
ctx.fillRect(x, y, boxWidth, boxWidth);
id++;
}
}
}
function draw() {
var id = 0;
for (var i = 0; i < dimension; i++) {
for (var j = 0; j < dimension; j++) {
var b = boxes[id];
var c = b.color;
ctx.fillStyle = c;
var col = to2d(id).col;
var row = to2d(id).row;
var x = col * boxWidth + 100;
var y = row * boxWidth + 100;
ctx.fillRect(x, y, boxWidth, boxWidth);
id++;
}
}
}
function getSurroundBoxes(box){
var result = [];
if (box.id+1 < dimension) result.push(boxes[box.id+1]);
if (box.id-1 >= 0) result.push(boxes[box.id-1]);
if (to2d(box.id+dimension).row < dimension) result.push(boxes[box.id+dimension]);
if (to2d(box.id-dimension).row >= 0) result.push(boxes[box.id-dimension]);
return result;
}
function getColor() {
return pallet[Math.floor(Math.random()*4)];
}
function to2d(id) {
var col = id % dimension;
var row = id / dimension;
return {row: Math.floor(row), col: col};
}
function toId(dim) {
var col = dim.col;
var row = dim.row;
return row * 20 + col;
}
function changeColor(box, color) {
boxes[box].color = color;
}
function convertboxes(color) {
if (doneBoxes.length == 0) {
doneBoxes.push(boxes[0]);
}
var pre = doneBoxes.length;
for(var i = 0; i < pre; i++) {
var b = doneBoxes[i];
var surround = getSurroundBoxes(b);
for (var x = 0, len = surround.length; x < len; x++) {
if ((surround[x].color == color)&& !contain(doneBoxes, surround[x])) {
doneBoxes.push(surround[x]);
}
}
}
var after = doneBoxes.length;
if (pre == after) {
for (var i = 0, len = doneBoxes.length; i < len; i++) {
boxes[doneBoxes[i].id].color = "grey";
}
draw();
} else {
convertboxes(color);
}
}
function contain(mother, child) {
for (var i = 0; i < mother.length; i++) {
if (mother[i].id == child.id) {
return true;
}
}
return false;
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body onload="init();">
<canvas id="color" width="1000" height="1000"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment