JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
<span id="output"></span>
CSS
canvas {
background: #fafafa;
}
JavaScript
var ColorChecker = function( options ) {
var canvas, ctx, output;
this.init = function() {
canvas = document.getElementById('canvas');
output = document.getElementById('output');
ctx = canvas.getContext("2d");
color = this.hexToRGB(options.searchedColor);
this.drawOnCanvas();
canvas.addEventListener('mousemove', function(e) {
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
var c = ctx.getImageData(mouseX, mouseY, 1, 1).data;
var foundColor = [c[0], c[1], c [2]];
var is_identical = foundColor.join() === color.join();
var message = is_identical == true ? 'red found' : 'not found';
output.innerHTML = message;
});
}
this.drawOnCanvas = function() {
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0, 20, 20);
}
this.hexToRGB = function( hex ) {
var r = parseInt((this.cutHex(hex)).substring(0,2),16);
var g = parseInt((this.cutHex(hex)).substring(2,4),16);
var b = parseInt((this.cutHex(hex)).substring(4,6),16);
return [r,g,b];
}
this.cutHex = function( hex ) {
return hex.replace("#",'');
}
this.init();
}
var colorChecker = new ColorChecker({
searchedColor: "#FF0000",
});