简体   繁体   中英

Detecting collision with color on a canvas in HTML5+JavaScript

I'm searching for a way in JavaScript how I can detect if an object like this:

var box = {
    x: 5,
    y: 19,
    width: 10,
    height: 5,
    draw: function(ctx){...draw Box on context "ctx"},
    touchingColor: function(ctx,color){...}
}

So basically what I'm looking for is a function touchingColor, that returns true if my box is touching the specified color in the specified context.

Is there a way to accomplish that, or do I need to keep track of the things I drawed on the canvas?

Well, I found a way to solve this issue :) Hopefully it helps someone...

var box = {
    x: 5,
    y: 19,
    width: 10,
    height: 5,
    draw: function(ctx){...draw Box on context "ctx"},
    touchingColor: function(ctx,r,g,b){
        var data = ctx.getImageData(this.x,this.y,this.width,this.height);
        for(var i=0;i<data.length;i+=4){
            if(
                data[i+0]==r&&
                data[i+1]==g&&
                data[i+2]==b
            ){
                return true;
            }
        }
        return false;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM