creator 实现点击事件透明区域穿透

const {ccclass, property} = cc._decorator;

@ccclass
export default class touch extends cc.Component {
    onLoad () {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouch, this)
        this.node._hitTest = this.hitTest.bind(this)
    }

    hitTest(point){
        var locationInNode = this.node.convertToNodeSpace(point);
        var size = this.node.getContentSize();
        let sprite = this.node.getComponent(cc.Sprite)
        if(sprite){
            var imgObj = sprite.spriteFrame.getTexture().getHtmlElementObj();
            if(this.onLucencyTouch(imgObj, locationInNode.x, size.height-locationInNode.y)){
                return true
            }else{
                return false
            }
        }
        return false
    }

    onLucencyTouch(img, x, y){
        var cvs = document.createElement("canvas");
        var ctx = cvs.getContext('2d');
        cvs.width = 1;
        cvs.height = 1;
        ctx.drawImage(img,x,y,1,1,0,0,1,1);
        var imgdata = ctx.getImageData(0,0,1,1);
        return imgdata.data[3];
    }

    onTouch(touch){
        console.log("----------", this.node.name)
    }
}

 

posted @ 2019-08-13 20:06  吴筱军  阅读(2378)  评论(0编辑  收藏  举报