Image map by alpha channel

前端 未结 3 1842
傲寒
傲寒 2020-12-16 05:26

Let\'s imagine that circle.png is a 400x400 px transparent background image with a c

3条回答
  •  萌比男神i
    2020-12-16 05:57

    thank you chris for this great answer

    I added a few lines to the code to handle with scaling the canvas

    so what I do now is creating a canvas of the exact pixel size the image has that is drawn on it. like (for an Image 220px*120px):

    
    

    and scale the canvas using css:

    #mainMenu_item{ width:110px; }

    and the adjusted isTransparentUnderMouse function looks like:

        var isTransparentUnderMouse = function (target, evnt) {
    
        var l = 0, t = 0;
        if (target.offsetParent) {
            var ele = target;
            do {
                l += ele.offsetLeft;
                t += ele.offsetTop;
            } while (ele = ele.offsetParent);
        }
    
        var x = evnt.pageX - l;
        var y = evnt.pageY - t;
    
        var initialWidth = $(evnt.target).attr('width');
        var clientWidth = evnt.target.clientWidth;
        x = x * (initialWidth/clientWidth);
    
        var initialHeight = $(evnt.target).attr('height');;
        var clientHeight = evnt.target.clientHeight;
        y = y * (initialHeight/clientHeight);
    
        var imgdata = target.getContext('2d').getImageData(x, y, 1, 1).data;
    
        if (
            imgdata[0] == 0 &&
            imgdata[1] == 0 &&
            imgdata[2] == 0 &&
            imgdata[3] == 0
        ){
            return true;
        }
        return false;
    };
    

提交回复
热议问题