http://jsfiddle.net/marco10507/ydtkbzoc/2/jsFiddle
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;
document.onkeydown = move;
By the way, I was told to use the function getImageData()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 JqueryjQuery was used, but I am not allowed to use JqueryjQuery. Please find the link below: