Skip to main content
2 of 4
added 1946 characters in body

Javascript canvas color detection

I am coding a game, and I need to detect the color of a rectangles on a canvas, by moving a character and touching them, so that a message will be displayed "this is magenta" and so on. Please find below the game and my coding, so that you will better understand me:

http://jsfiddle.net/marco10507/ydtkbzoc/2/

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");


/*moving grey character*/
var xPos = 0;
var yPos = 0;

var bucketWidth = 100;
var bucketHeight = 10;

context.fillStyle = "grey";
context.fillRect(xPos, yPos, bucketWidth, bucketHeight);
context.strokeRect(xPos, yPos, bucketWidth, bucketHeight);

/*static red character*/
var xPos2 =  canvas.width / 2;
var yPos2 =  canvas.height / 2;

var bucketWidth2 = 100;
var bucketHeight2 = 10;

context.fillStyle = "red";
context.fillRect(xPos2, yPos2, bucketWidth2, bucketHeight2);

/*static magenta character*/

var bucketWidth3 = 100;
var bucketHeight3 = 10;

var xPos3 =  canvas.width / 2;
var yPos3 =  - bucketHeight3 - bucketHeight3 + canvas.height / 2;

context.fillStyle = "magenta";
context.fillRect(xPos3, yPos3, bucketWidth3, bucketHeight3);

/*Function to move the grey character from left to right and from top to button*/

function move(e){

if (e.keyCode === 37 && xPos > 0 && xPos <= canvas.width-bucketWidth){
    xPos -= bucketWidth;
} else if (e.keyCode === 39 && xPos >= 0 && xPos < canvas.width-bucketWidth){
    xPos += bucketWidth;
}  else if (e.keyCode === 40 && yPos >= 0 && yPos < canvas.height-bucketHeight){/*down arrow*/
    yPos += bucketHeight;
}  else if (e.keyCode === 38 && yPos > 0 && yPos <= canvas.height-bucketHeight){ /*up arrow*/
    yPos -= bucketHeight;
}

           

canvas.width= canvas.width;
    
    
context.fillStyle = "grey";
context.fillRect(xPos, yPos, bucketWidth, bucketHeight);
context.strokeRect(xPos, yPos, bucketWidth, bucketHeight);

    
context.fillStyle = "red";
context.fillRect(xPos2, yPos2, bucketWidth2, bucketHeight2);

    
context.fillStyle = "magenta";
context.fillRect(xPos3, yPos3, bucketWidth3, bucketHeight3);


    
}

document.onkeydown = move;

By the way I was told to use the function getImageData(), but I could not apply the function by moving the character. Somebody send me an example, but it is working by using the mouse and Jquery was used, but I am not allowed to use Jquery. Please find the link below:

http://jsfiddle.net/m1erickson/gpy9fccu/

Thank you,