Click area on sprite in canvas

后端 未结 2 1667
心在旅途
心在旅途 2020-12-06 07:30

I\'m creating a game in Javascript. currently the sprites are div elements with a background image that is updated to create animation. I have heard that if I make the eleme

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 08:01

    You could have the background be transparent and check images for transparency at the clicked pixel. Here's some code from one of my game prototypes:

    function getAlphaInImage(img, x, y) {
        var tmp = document.createElement("CANVAS");
        tmp.setAttribute('width', img.width);
        tmp.setAttribute('height', img.height);
        var tmpCtx = tmp.getContext('2d');
        tmpCtx.drawImage(img, 0, 0);
        var imageData = tmpCtx.getImageData(x, y, 1, 1);
        var alpha = imageData.data[3];
        tmp = null;
        imageData = null;
        return alpha;
    }
    

    Before calling this I first check if the mouseclick was within the whole image.

提交回复
热议问题