Get pixelcolor of CSS Background Image

3k views Asked by At

I need to get the color of any pixel my mousepointer is currently hovering. I found several solutions for canvas elements, but none for a background image defined in CSS for a element.

How can I achieve this?

1

There are 1 answers

4
jwatts1980 On BEST ANSWER

Combining the answers from Get a CSS value with JavaScript and How to get a pixel's x,y coordinate color from an image?, I was able to simulate what you are looking for: JSFiddle

<html>
<head>
    <style type="text/css">
        #test {
            background-image: url('http://jsfiddle.net/img/logo.png');
            background-color: blue;
            background-repeat: no-repeat;
            height: 30px;
            width: 100%;
        }

        #hidden {
            display: none;
        }
    </style>
    <script type="text/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 img = document.getElementById("i1");
            img.src = path;

            var canvas = document.getElementById("c1");
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

            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];
        };
    </script>
</head>
<body>
    <div id="test"></div>
    <div id="hidden">
        <img id="i1" src="" />
        <canvas id="c1"></canvas>
    </div>
    <div id="values"></div>
</body>
</html>

I retrieved the computed style (var style = window.getComputedStyle(div);) outside of the mouse move function for performance reasons, but if the background image is going to change dynamically, then it may need to be moved into the function.

There are some possible browser constraints for using getComputedStyle.

SCALING You could try editing the code to adjust for the scale:

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);

This also includes a change to the CSS: JSFiddle