JSFiddle - React, Tailwind, and code Playground

by henser

HTML

<canvas id="c"></canvas>
<img id="s"...

JavaScript

var c = document.getElementById('c'),
	  // status = document.getElementById('status'),
		img = new Image(),
    pixel_size = 6;
		
img.onload = halftone;
img.src = document.getElementById('s').src;

/* c.addEventListener("mousemove", function(e) {
    let pos = findPos(this),
        x = e.pageX - pos.x,
        y = e.pageY - pos.y,
        coord = "x=" + x + ", y=" + y,
        c = this.getContext('2d'),
        p = c.getImageData(x, y, 1, 1).data,
        hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);

    status.textContent = coord + " || " + hex;
}); */

function halftone() {
  var w = c.width = img.width,
      h = c.height = img.height,
      display = c.getContext('2d');

  display.fillStyle = '#fff';
  display.fillRect(0, 0, img.width, img.height);

  drawColor(pixel_size, 'y', w, h, display);
  drawColor(pixel_size, 'm', w, h, display);
  drawColor(pixel_size, 'c', w, h, display);
  drawColor(pixel_size, 'k', w, h, display);
}

function drawColor(pixel_size, color, w, h, display) {
    var ow = w + h,
        oh = h + w,
        c = document.createElement('canvas'),
        source;

    // source
    // add margins to avoid getImageData's out of range errors
    c.width = ow + pixel_size;
    c.height = oh + pixel_size;

    source = c.getContext('2d');
    source.drawImage(img, 0, 0);

    for(var y = 0; y < oh; y += pixel_size) {

      for(var x = 0; x < ow; x += pixel_size) {
        var pixels = source.getImageData(x, y, pixel_size, pixel_size).data,
            sum = 0,
            count = 0;

        for(var i = 0; i < pixels.length; i += 4) {

          if(pixels[i + 3] === 0) {
              continue;
          }

          var r = 255 - pixels[i],
              g = 255 - pixels[i + 1],
              b = 255 - pixels[i + 2],
              k = Math.min(r, g, b);

          if (color !== 'k' && k === 255) {
              sum += 0;
          } else if (color === 'k') {
              sum += k / 255;
          } else if (color ===...