Search code examples
javascriptcanvaskeypress

Changing shape's coords on keypress


I have a <canvas/>, and a shape rendering on it. I am trying to change the shape's coordinates on keypress, but am having no luck.

Here's my source:

var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var radius = 35;

var xPos = 0;

context.beginPath();
context.arc(xPos, 0, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke(); 

$(document).keypress(function(event) {
    if (event.which == 100) {
        xPos++;
    }
});

Another issue I am having is figuring out what keys are what number? Is there a chart somewhere? I saw two conflicting values on different sites.


Solution

  • The following article http://atomicrobotdesign.com/blog/htmlcss/move-objects-around-the-canvas-using-the-keyboard-and-jquery/ goes into great detail using jQuery to reference a Canvas object and then manipulate that object.

    It also examines how to adjust the position of that Canvas object in response to keystrokes entered by the user.

    Hope that helps.