Search code examples
javascripthtmlcanvaskineticjs

KineticJS Shape Movement with Keydown


I have made a shape that I move with the help of arrow keys (keydown event) using transitionTo from KineticJS.

I have 2 problems:

1. After pressing the key the movement of the shape has a short delay. How do I remove the delay?

2. How do I make the shape move diagonally with two arrow keys pressed at the same time?Here is the javascript:

var stage = new Kinetic.Stage({
    container: 'container',
    width: screen.width,
    height: 500
});
var layer = new Kinetic.Layer();

var circle = new Kinetic.Circle({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    radius: 70,
    fill: 'yellow',
    stroke: 'black',
    strokeWidth: 4
});

// add the shape to the layer
layer.add(circle);

// add the layer to the stage
stage.add(layer);

window.addEventListener('keydown', function(e) {
    if (e.keyCode == 37) { //Left Arrow Key
        setTimeout(function () {
            circle.transitionTo({
                x: circle.getX() - 10,
                y: circle.getY(),
                duration: 0.01
            })
        }, 0);
    }
    if (e.keyCode == 38) { //Up Arrow Key
        setTimeout(function () {
            circle.transitionTo({
                x: circle.getX(),
                y: circle.getY() - 10,
                duration: 0.01
            })
        }, 0);
    }
    if (e.keyCode == 39) { //Right Arrow Key
        setTimeout(function () {
            circle.transitionTo({
                x: circle.getX() + 10,
                y: circle.getY(),
                duration: 0.01
            })
        }, 0);
    }
    if (e.keyCode == 40) { //Top Arrow Key
        setTimeout(function () {
            circle.transitionTo({
                x: circle.getX(),
                y: circle.getY() + 10,
                duration: 0.01
            })
        }, 0);
    }
});

Fiddle: http://jsfiddle.net/uUWmC/1/


Solution

  • For the delay, you can unwrap setTimeout and transitionTo like the following;

    window.addEventListener('keydown', function(e) {
        if (e.keyCode == 37) //Left Arrow Key
            circle.attrs.x -= 10;
        if (e.keyCode == 38) //Up Arrow Key
            circle.attrs.y += 10;
        if (e.keyCode == 39) //Right Arrow Key
            circle.attrs.x += 10;
        if (e.keyCode == 40) //Top Arrow Key
            circle.attrs.y -= 10;
        layer.draw();
    });
    

    For the diagonal move, you cannot press two arrow keys at the same time. This is your operating system limit. You can press it with alt key, ctrl key ... etc though.