Last Updated: February 25, 2016
·
4.784K
· bahlor

JS-Snippet: Check for image transparency of hovered coordinates

Just a very quick hint / snippet on checking, if the current hovered position on the image is transparent or not.

The function

function isTransparent(e) {
        var x = e.pageX - this.offsetLeft,
            y = e.pageY - this.offsetTop;

        var canvas = document.getElementById('imgcheck-canvas') || (function(_this) { var e = document.createElement('canvas'); e.setAttribute('width',_this.width); e.setAttribute('height',_this.height); e.setAttribute('id',_this.id+'-canvas'); e.setAttribute('style','display:none;');document.body.appendChild(e);var cx=e.getContext('2d');cx.drawImage(_this,0,0,_this.width,_this.height); return e; })(this);
        if(canvas.getContext === undefined) { return false; }
        var ctx = canvas.getContext('2d');

        output.innerHTML = ((ctx.getImageData(x,y,1,1).data[3] == 0) ? true:false);
    }

So what is happening there? Its actually pretty easy, this function gets called onmousemove at images. The script calculates the x and y location on the current image, also subtracting the offset position of the hovered element. After this, it checks if this image already got hovered and if we already have created a canvas for this, otherwise we are creating and assigning a new canvas using an anonymous function.

This is basically it. Now we just need to use canvas.context.getImageData(x,y,w,h) to get the rgba values of the desired point. The values are assigned to an array named data and always in the following order:

ImageData

data[0] // r 
data[1] // g 
data[2] // b
data[3] // alpha

They all have a value from 0-255 where 0 is not visible and 255 is fully visible. So now we just have to get the 4th (index 3) value of the array and check if its a 0 to make sure the currently hovered pixel is transparent.

Example

jsFiddle Demo