JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById('canvas'),
cnv = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var countX = 0;
var countY = 0;
function init(){
bg = new draw_frame("#eee", 0, 0, canvas.width, canvas.height);
player = new draw_frame("#999", 0, 80, 20, 20);
block = new draw_frame("red", 280, 60, 30, 80);
draw();
conrol();
bg.draw();
block.draw();
}
function draw(){;
bg.draw();
player.draw();
block.draw();
}
function draw_frame(color, x, y, w, h){
this.color = color;
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.draw = function(){
cnv.fillStyle = this.color;
cnv.fillRect(this.x, this.y, this.width, this.height);
}
}
function conrol(){
document.onkeydown = function(e){
switch(e.keyCode){
case 39:
if(check(player.x)){
player.x = countX+=10;
draw();
}
break;
case 37:
if(check(player.x)){
player.x = countX-=10;
draw();
}
break;
case 40:
player.y = player.y - (countY-5);
draw();
break;
case 38:
player.y = player.y - (countY+5);
draw();
break;
default:
console.log(e.keyCode);
break;
}
}
}
function check(){
if( player.x + player.width >= block.x &&
player.x <= block.x + block.width &&
player.y + player.height >= block.y &&
player.y <= block.y + block.height){
return false;
}
return true;
}
init();