JSFiddle - React, Tailwind, and code Playground

by Ernest Fayzullin

HTML

<div id="result"></div>
<canvas id="myCanvas" width="400" height="265" />

CSS

#result {
    width: 230px;
    height: 250px;
    background-color: #efefef;
    border: 7px dashed #aaa;
    float: right;
}
#myCanvas {
    cursor: crosshair;
}

JavaScript

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function drawInnerGradient() {
    ctx.beginPath();
    var gradient= ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop(1, '#ff0000');
    gradient.addColorStop(0, '#330000');
    ctx.fillStyle = gradient;
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fill();
    ctx.closePath();
}

var ctx, canvas;

$(document).ready(function() {
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    
    drawInnerGradient();
    
    $('#myCanvas').click(function(e) {
        var pos = findPos(this);
        var x = e.pageX - pos.x;
        var y = e.pageY - pos.y;
        var coord = "x=" + x + ", y=" + y;
        var c = this.getContext('2d');
        var p = c.getImageData(x, y, 1, 1).data; 
        var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
        
        console.log(hex);
        $('#result').css('background-color', hex);
    });
})