SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post Keybourd inputs?

    Im wrote a code to try and make an image drawn on a canvas move when a button is pressed, but its no working, can someone tell me where i went wrong in the code?

    const FPS = 30;
    var x = 0;
    var y = 0;
    var image = new Image();
    image.src = "jsplatformer1-smiley.jpg";
    var canvas = null;
    var context2D = null;
    var left = false
    var up = false
    var right = false
    var down = false
    window.onload = init;

    function init()
    {
    canvas = document.getElementById('canvas');
    context2D = canvas.getContext('2d');
    setInterval(draw, 1000 / FPS);

    }

    function draw(event)
    {
    context2D.clearRect(0, 0, canvas.width, canvas.height);
    context2D.drawImage(image, x, y);

    if (event.keyCode == 39) {
    x += 1;
    }


    }

  2. #2
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    Posts
    387
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    The event object isn't getting passed to your function. You need to listen for the keydown event, rather than just run the draw function every x milliseconds:

    Code JavaScript:
    function init() {
        canvas = document.getElementById('canvas');
        context2D = canvas.getContext('2d');
        document.addEventListener('keydown', draw, false);
    }
     
    function draw(event) {
        context2D.clearRect(0, 0, canvas.width, canvas.height);
        context2D.drawImage(image, x, y);
        if (event.keyCode == 39) {
            x += 1;
        }
    }
    I'm the web overlord for Graphic Business Systems


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •