I need to set a border on background.png so player.png cant go past it or off of it. I used JS and HTML. Everything else works just fine, please answer as soon as possible. :)
Here is my code:
Javascript:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var background = new Image();
background.src = "images/background.png";
background.onload = function() {
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
start();
}
var image = new Image();
var imageX = 0;
var imageY = 0;
function start(){
image.src = "images/player.png";
image.onload = function(){
imageX = 35;
imageY = 35;
ctx.drawImage(image, imageX, imageY);
};
}
document.addEventListener("keydown", keyDownHandler);
function keyDownHandler(event){
event.preventDefault();
event.stopPropagation();
if (event.keyCode == 65) {
imageX -= 13;
} else if (event.keyCode == 87) {
imageY -= 13;
} else if (event.keyCode == 68) {
imageX += 13;
} else if (event.keyCode == 83) {
imageY += 13;
}
redraw();
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
ctx.drawImage(image, imageX, imageY);
}
Html:
<!DOCTYPE html>
<html>
<head>
<title>blow shoot</title>
</head>
<body>
<canvas id= "myCanvas" width= "500" height= "250">
<script src="main.js"></script>
</canvas>
</body>
</html>
Images:
You can add a strokeRect function:
ctx.strokeRect(x,y,w,h)
where x,y is the coordinate of the left upper corner of the image, and the w,h is the dimension of the image.
If you want to make it stay out, -1 on x,y +2 on w,h to have a 1px offset on every side.