JSFiddle - React, Tailwind, and code Playground

by Michael Prosser

HTML

<canvas id=canvas width=500 height=500></canvas>

JavaScript

var ctx = canvas.getContext('2d'),
    img = new Image;
img.onload = draw;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/1alt1303g9zpemd/UFBxY.png";
var outline, 
    outlineCtx;

function draw(color) {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // onload
  if(typeof color !== 'string') color = 'red';

  var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
      s = 5,  // scale
      i = 0,  // iterator
      x = 5,  // final position
      y = 5;
  
  // draw images at offsets from the array scaled by s
  for(; i < dArr.length; i += 2)
    ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
  
  // fill with color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillStyle = color;
  ctx.fillRect(0,0,canvas.width, canvas.height);
  
  // keep only the outline
  ctx.globalCompositeOperation = "destination-out";
  ctx.drawImage(img, x, y);

  // store the imageData in a new Canvas
  outline = canvas.cloneNode(true);
  outlineCtx = outline.getContext('2d')
  outlineCtx.drawImage(canvas,0,0);

  // draw image in original mode
  ctx.globalCompositeOperation = "source-over";
  ctx.drawImage(img, x, y);
}

canvas.onclick = function(e){
   var rect = canvas.getBoundingClientRect();
   var x = e.clientX-rect.left,
       y = e.clientY-rect.top;
  // not transparent ?
  if(outlineCtx.getImageData(x,y,1,1).data[3]===255){
    draw('green');
    }
  else
    draw('red');
  }
  }