Сообщение от drakulawz
|
по диагонали
|
или так с setTimeout
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<script>
try {
'code' in KeyboardEvent.prototype || Object.defineProperty(KeyboardEvent.prototype, 'code', {
get: function () { return { 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown' }[this.keyCode] }
})
} catch (e) {}
</script>
</head>
<body>
<canvas width="200" height="100" id="myCanvas" style="border: 1px solid red"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var rec = {};
rec.x = 10;
rec.y = 10;
rec.width = 50;
rec.height = 25;
rec.step = 5;
rec.color = 'red';
rec.moveup = function () {
this.y = Math.max(this.y - this.step, 0);
};
rec.movedown = function () {
this.y = Math.min(this.y + this.step, canvas.height - this.height);
};
rec.moveleft = function () {
this.x = Math.max(this.x - this.step, 0);
};
rec.moveright = function () {
this.x = Math.min(this.x + this.step, canvas.width - this.width);
};
rec.draw = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
rec.draw();
var move = {};
var timer;
document.onkeydown = function (e) {
e.preventDefault();
if(move[e.code]) return;
if (e.code == 'ArrowUp') {rec.moveup();move.ArrowUp = true }
else if (e.code == 'ArrowDown') {rec.movedown();move.ArrowDown = true }
else if (e.code == 'ArrowLeft') {rec.moveleft();move.ArrowLeft = true}
else if (e.code == 'ArrowRight') {rec.moveright();move.ArrowRight = true}
else return;
window.clearTimeout(timer);
timer = window.setTimeout(rec.draw.bind(rec), 120);
};
document.onkeyup = function (e) {
if (e.code == 'ArrowUp') move.ArrowUp = false;
else if (e.code == 'ArrowDown') move.ArrowDown = false;
else if (e.code == 'ArrowLeft') move.ArrowLeft = false;
else if (e.code == 'ArrowRight') move.ArrowRight = false;
};
</script>
</body>
</html>