JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test"></div>
<img id="i1" src="" />
<div id="hidden">
<canvas id="c1"></canvas>
</div>
<br /><br />
<div id="values"></div>
CSS
body { background-color: lightblue; }
#test {
background-image: url('/img/logo.png');
background-color: blue;
background-repeat: no-repeat;
/* background-size: contain; */
background-size: 250px 150px;
width: 250px;
height: 150px;
}
#hidden {
display: none;
}
JavaScript
var div = document.getElementById("test");
var style = window.getComputedStyle(div);
div.onmousemove = function(e) {
var path = style.getPropertyValue('background-image');
path = path.substring(4, path.length-1);
var h = parseInt(style.getPropertyValue("width")),
w = parseInt(style.getPropertyValue("height"));
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = h;
canvas.height = w;
canvas.getContext('2d').drawImage(img, 0, 0, w, h);
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
var values = document.getElementById("values");
values.innerHTML =
'R: ' + pixelData[0] +
'<br>G: ' + pixelData[1] +
'<br>B: ' + pixelData[2] +
'<br>A: ' + pixelData[3] +
'<br>div.height: ' + style.getPropertyValue("height") +
'<br>div.width: ' + style.getPropertyValue("width");
};