I’m trying to move something on the canvas upon pressing the left key.
$(document).ready(function () {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0); // draw the image at the right coords
ctx.drawImage(img,110,110); // draw the image at the right coords
ctx.save();
};
img.src = 'tiles/processed/1_grass.png'; // Set source path
function draw() {
ctx.translate(20,0);
};
draw();
draw();
draw();
$(document).keydown(function(e) {
if (e.keyCode == 37) {
draw();
};
});
});
Now, it appears the three draw();’s work, but the one inside the function doesn’t.
Am I totally missing the concept of canvas (in that it is static by nature, and has to be entirely re-drawn all the time) or is there something I’m doing wrong?
(ps.: I’m using Jquery as well)
Cheers!
You’re never actually redrawing the canvas. You draw once (
img.onload) and otherwise only translate the canvas.Your
drawfunction should clear the canvas and redraw the image.here is a simple example, building on your code:
demo: http://jsfiddle.net/Vx2kQ/
Personally, though, I would not use
translateto handle that movement. I would use some x/y coords, stored in a private variable. On keydown I would then manipulate those coords and redraw.