Reputation: 818
I've been trying to do something that seems like it should be really simple, but I've been hitting a wall. I want to write javascript code which takes a image that has been drawn inside the the canvas tag and moves it via keyboard input. When I press the right arrow key, I want the image to move right. When I press the left arrow key, I want the image to move left. I want it to keep moving until I release the key, I'm not interested in something that just slides over a bit with each key press. Here is what I've come up with so far:
<html>
<body onload="load_image()">
<canvas id="myCanvas" width="320" height="240" style="border:1px solid #000000;">
<img id="testpic" src="testpic.png">
</canvas>
<script>
function load_image() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("testpic");
ctx.drawImage(img,10,10);}
document.addEventListener('keydown', function(event) {
if (event.keyCode == 37) {
// CODE THAT STARTS LEFT IMAGE MOVEMENT GOES HERE.
}
else if (event.keyCode == 39) {
// CODE THAT STARTS RIGHT IMAGE MOVEMENT GOES HERE.
}
}, true);
document.addEventListener('keyup', function(event) {
if (event.keyCode == 37) {
// CODE THAT STOPS LEFT IMAGE MOVEMENT GOES HERE.
}
else if (event.keyCode == 39) {
// CODE THAT STOPS RIGHT IMAGE MOVEMENT GOES HERE.
}
}, true);
</script>
</body>
</html>
I've been trying examples from several websites, but none of them work. The best I can do is redraw the image over and over with key presses, which will not work for me. Any tips or guidance would be greatly appreciated. If you present me with working code, I will love you!
Upvotes: 1
Views: 3358
Reputation: 3062
I made a working fiddle of what you want here: https://jsfiddle.net/uu4jqpqy/1/
The main point is that you have to have setInterval
do a loop of redraws in the right direction on a key down, and key up clears that Interval:
if (event.keyCode == 37) {
// CODE THAT STARTS LEFT IMAGE MOVEMENT GOES HERE.
if(!leftPointer) {
leftPointer = setInterval(function () {
xval = xval - 1;
ctx.clearRect(0, 0, c.width, c.height);
ctx.drawImage(img,xval,yval);
}, speed)
}
}
and
if (event.keyCode == 37) {
// CODE THAT STOPS LEFT IMAGE MOVEMENT GOES HERE.
clearInterval(leftPointer);
}
You also have to make some of the variables in an outer scope to get this to work.
Upvotes: 2