Reputation: 197
I'm only new to JavaScript and I'm having a problem with my code where I'm trying to move an object around the canvas with user input.
It works just fine using Firefox to run it but with Chrome the user input to move the square doesn't work and I was wondering why this is?
<!DOCTYPE html>
<html>
<head>
<canvas id = "gameCanvas" width="400" height="400" style = "border:1px solid #000000;"></canvas>
<style type="text/css"></style>
</head>
<body>
<script type="text/javascript">
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgb(255, 0, 0)";
var snake = {
x: 5
, y: 5
};
function drawSnake() {
ctx.fillRect(snake.x ,snake.y,20,20);
}
window.addEventListener("keypress", function(event) {
if (event.keyCode == 39)
snake.x += 5;
else if (event.keyCode == 37)
snake.x -= 5;
else if (event.keyCode == 38)
snake.y -= 5;
else if (event.keyCode == 40)
snake.y += 5;
drawSnake();
});
drawSnake();
</script>
</body>
</html>
Upvotes: 3
Views: 1179
Reputation: 441
You have to change your keypress
event to keydown
to make it work in IE and Chromium based browsers.
Upvotes: 3