JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<h4>Click in region(s) within the grid square.</h4>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body{ background-color: ivory; }
#canvas{border:1px solid red;}
JavaScript
// canvas and mousedown related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
// save canvas size to vars b/ they're used often
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
// define the grid area
// lines can extend beyond grid but
// floodfill wont happen outside beyond the grid
var gridRect = {
x: 50,
y: 50,
width: 200,
height: 200
}
drawGridAndLines();
// draw some test gridlines
function drawGridAndLines() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
// Important: the lineWidth must be at least 5
// or the floodfill algorithm will "jump" over lines
ctx.lineWidth = 5;
ctx.strokeRect(gridRect.x, gridRect.y, gridRect.width, gridRect.height);
ctx.beginPath();
ctx.moveTo(75, 25);
ctx.lineTo(175, 275);
ctx.moveTo(25, 100);
ctx.lineTo(275, 175);
ctx.stroke();
}
// save the original (unfilled) canvas
// so we can reference where the black bounding lines are
var strokeData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
// fillData contains the floodfilled canvas data
var fillData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
// Thank you William Malone for this great floodFill algorithm!
// http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/
//////////////////////////////////////////////
function floodFill(startX, startY, startR, startG, startB) {
var newPos;
var x;
var y;
var pixelPos;
var neighborLeft;
var neighborRight;
var pixelStack = [
[startX, startY]
];
while (pixelStack.length) {
newPos = pixelStack.pop();
x = newPos[0];
y = newPos[1];
// Get current pixel position
pixelPos = (y * canvasWidth +...