I have some code that takes a array of colors and creates a grid of rectangles on a canvas based on the data: https://jsfiddle.net/yzjeLm5r/2/
Html:
<canvas id="canvas" width="100" height="100">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
Js:
var my_canvas = document.getElementById('canvas'),
context = my_canvas.getContext("2d");
const cellSize = 20;
const arr = ['#FF0000', '#FF0000', null, null, '#0000FF',
'#FF0000', '#FF0000', '#FF0000', null, '#0000FF',
'#FF0000', null, '#FF0000', null, '#0000FF',
'#FF0000', '#FF0000', '#FF0000', null, '#0000FF',
'#FF0000', '#FF0000', '#0000FF', '#0000FF', '#0000FF'
]
let col = 0;
let row = 0;
arr.forEach((item) => {
if (item) {
context.fillStyle = item;
context.fillRect(
col * cellSize,
row * cellSize,
cellSize,
cellSize
);
}
if (col === 4) {
col = 0;
row += 1;
} else {
col += 1;
}
});
Outcome:
I now need to find a way to create a stroke around the entire shape, as well as any 'island' pieces on the inside, to separate it from the blank regions (it does not separate the red from blue, just the outer borders). So it would look like this:
However, I can't find any viable way to do this. Some methods suggest creating the stroke, change the composition to context.globalCompositeOperation = "destination-out"; and then adding the fill which would 'merge' any overlapping pieces, but these don't actually overlap they just touch. Other solutions recommend just tracing around the edges of the complete shape with stoke ctx.moveTo() and then applying stroke, but since I'm filling data using fillRect() I dont have the coordinates to trace around it.
Is there anyway to get the stroke I need?

