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.
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.