简体   繁体   中英

Altering HTML5 Canvas element on keydown (JS, Jquery)

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 draw function should clear the canvas and redraw the image.


here is a simple example, building on your code:

$(function () {
  var ctx = document.getElementById('canvas').getContext('2d');

  function draw() {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.restore();

    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, 20, 20);
  };

  draw();
  $(document).keydown(function(evt) {
    switch(evt.keyCode) {
      case 37:
        ctx.translate(-5, 0);
        break;
      case 38:
        ctx.translate(0, -5);
        break;
      case 39:
        ctx.translate(5, 0);
        break;
      case 40:
        ctx.translate(0, 5);
        break;
    }

    draw();
  });
});​

demo: http://jsfiddle.net/Vx2kQ/


Personally, though, I would not use translate to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM