https://jsfiddle.net/b6sruud6/3/const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
canvas.width = 500;
canvas.height = 500;
class Square{
constructor(color, position, size, speed){
this.color = color;
this.x = position.x;
this.y = position.y;
this.speed = speed || {x:0,y:0};
this.width = size.width;
this.height = size.height
}
render(ctx){
this.x += this.speed.x;
this.y += this.speed.y;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
const player = new Square('#f00', {x:100,y:100}, {width:16, height:16});
const deltaCoord = 5;
const canvasColor = '#fff';
Rx.Observable
.fromEvent(document, 'keydown')
.map(
e => {
const s = {x:0,y:0}
if (e.keyCode == 37) s.x -= deltaCoord;
if (e.keyCode == 38) s.y -= deltaCoord;
if (e.keyCode == 39) s.x += deltaCoord;
if (e.keyCode == 40) s.y += deltaCoord;
console.log(s)
return s;
}
)
.startWith({x:0,y:0})
.subscribe(render);
function render(direction) {
ctx.fillStyle = canvasColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
player.speed = direction;
player.render(ctx);
}