JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="practice" class="practice" width=300 height=300>
Your browser does not support HTML5. Please consider upgrading.
</canvas>
JavaScript
function rectangle() {
this.x = 0;
this.y = 0;
this.color = "rgb(0,0,5)";
this.height = 0;
this.width = 0;
this.show = function(canvas) {
canvas.fillRect(this.x, this.y, this.width, this.height);
}
}
$(document).ready(function() {
var canvas = document.getElementById('practice');
var ctx = canvas.getContext('2d');
var square = new rectangle();
if (ctx) {
square.x = 50;
square.y = 50;
square.height = 10;
square.width = 10;
square.show(ctx);
}
else {
//browser doesn't support html5
}
var up = 38;
var down = 40;
var left = 37;
var right = 39;
$(document).bind('keyup', function(e) {
canvas.width = canvas.width;
var code = e.which;
if (code == down) {
square.y += 1;
}
else if (code == up) {
square.y -= 1;
}
else if (code == left) {
square.x -= 1;
}
else if (code == right) {
square.x += 1;
}
square.show(ctx);
});
});