Reputation: 4966
I'm using react and I have this code which accurately detects a background-color when I hover but when using a gradient it replies with the entire "linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)"
. Is there a way I can detect any color I'm hovering over much like in dev tools using js?
const getColor = (div, e) => {
console.log(div, e, e.target, window.getComputedStyle(e.target).getPropertyValue("backgroundImage"))
let color = window.getComputedStyle(e.target).getPropertyValue("background-color");
//let color = window.getComputedStyle(e).getPropertyValue("background-color")
//console.log(color)
setTheme(color)
}
return (
<div className="row">
<div className="col-md-12">
<div className="row">
<div className="col-md-12" onMouseOver={(e) => getColor(this,e)}>
<br />
<div style={{backgroundImage: "linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)"}}>Blue</div>
<div style={{backgroundColor:"red"}}>Red</div>
<div style={{backgroundColor:"yelllow"}}>Yellow</div>
.......
Upvotes: 0
Views: 1085
Reputation: 178
JavaScript doesn't have such information about the regular html nodes (unless browser extensions are an option). What you're looking for can be done using canvas where you can process each pixel.
Checkout this snippet: http://jsfiddle.net/89wLbh3q/14/
$('#example').mousemove(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);
$('#status').html(coord + "<br>" + hex);
});
If canvas is not an option, try to render the CSS gradient in a hidden canvas. You can also convert html to a hidden canvas using html2canvas.
Upvotes: 1