JSFiddle - React, Tailwind, and code Playground

by unsign3d

HTML

<canvas id="box" width="640" height="480"> </canvas>

JavaScript

var ctx = document.getElementById("box").getContext("2d");
ctx.fillRect(10, 10, 100, 100);
var imgData = ctx.getImageData(0, 0, 640, 480);
var pixels = imgData.data;
var x, y;



document.getElementById("box").addEventListener('mousemove', ev_mousemove, false);

checkMouse();

function ev_mousemove (ev) {
  if (ev.layerX || ev.layerX == 0) { 
    x = ev.layerX;
    y = ev.layerY;
  } else if (ev.offsetX || ev.offsetX == 0) { 
    x = ev.offsetX;
    y = ev.offsetY;
  }
}

function checkMouse()
{
    ctx.clearRect(0, 0, 640, 480);
    ctx.fillText("x: " + x + " y: " + y, 300, 300);
    ctx.fillText(pixels[x * y * 4], 300, 320);
    ctx.fillText(pixels[(x * y * 4) + 1], 300, 320);
    ctx.fillText(pixels[(x * y * 4) + 2], 300, 340);
    ctx.fillText(pixels[(x * y * 4) + 3], 300, 350);
    ctx.fillRect(10, 10, 100, 100);
    
    if (pixels[x * y * 4]) 
    {    
        alert("aqui");
    }
    setTimeout(checkMouse, 100);   
}