0
votes

In a canvas, an object is moved according to the arrow keys of keyboard. But I want to add arrow keys controls in screen so, that user can move that object with mouse or with touch in ipad or from smart phone devices.

JsFiddle

All i want to do is, trigger keyboard events on the mousedown according to the direction buttons.

$('#down').click(function(e)
{
    //?????
});

Html

<div class="keys" id="down">Down</div>
<div class="keys" id="up">Up</div>
<div class="keys" id="left">Left</div>
<div class="keys" id="right">Right</div>

Javascript

function update() {

    // check the keys and do the movement.
    if (keys[38]) {
        if (velY > -speed) {
            velY--;
        }
    }

    if (keys[40]) {
        if (velY < speed) {
            velY++;
        }
    }
    if (keys[39]) {
        if (velX < speed) {
            velX++;
        }
    }
    if (keys[37]) {
        if (velX > -speed) {
            velX--;
        }
    }

    // apply some friction to y velocity.
    velY *= friction;
    y += velY;

    // apply some friction to x velocity.
    velX *= friction;
    x += velX;

    // bounds checking
    if (x >= 295) {
        x = 295;
    } else if (x <= 5) {
        x = 5;
    }

    if (y > 295) {
        y = 295;
    } else if (y <= 5) {
        y = 5;
    }

    // do the drawing
    ctx.clearRect(0, 0, 300, 300);
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2);
    ctx.fill();

    setTimeout(update, 10);
}

update();

// key events
document.body.addEventListener("keydown", function (e) {
    keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
    keys[e.keyCode] = false;
});

How do i trigger keyboard event from the mousedown or touch event.

2
This should help you out mate html5rocks.com/en/mobile/touch - Canvas
Nice little sim that :) Think maybe using touches on the canvas, looking at where the event is relative to the ball to decide on the direction of movement would make a nice initiative touch. Also means less listeners to resister! - nepeo

2 Answers

1
votes

I have a long procedure, of adding multiple events, but its very simple.

function upTrue(){keys[38] = true;}
function upFalse(){keys[38] = false;}

var upKey = document.getElementById('up');
upKey.addEventListener('mousedown', upTrue);
upKey.addEventListener('touchstart', upTrue);
upKey.addEventListener('mouseup', upFalse);
upKey.addEventListener('touchend', upFalse);

Throughly you can add events for other three directions

0
votes

Why would you do this when you can use the touch events? you have more than touch event there, you have some event like move finger, touch the screen and more