JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="gameBoard" width="400" height="200" style="border:1px solid #000000;"></canvas>
<center>
<div>
<button id="up" type="button">Up</button>
</div>
<div>
<button id="left" type="button">Left</button>
<button id="right" type="button">Right</button>
</div>
<div>
<button id="down" type="button">Down</button>
</div>
</center>
JavaScript
///
/// Don't forget to deal with onload for images
///
///
///
"use strict";
// Variables
var canvas = document.getElementById('gameBoard');
var ctx = canvas.getContext('2d');
var FPS = 1;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / FPS);
};
var upButton = document.getElementById('up');
var downButton = document.getElementById('down');
var leftButton = document.getElementById('left');
var rightButton = document.getElementById('right');
var playerImg = new Image();
playerImg.src = 'http://rlv.zcache.com.au/red_skull_crossbones_sticker-r317f2e086e0741138b882fe4bd9e18c6_v9waf_8byvr_50.jpg';
// Player object
var player = {
x: 10,
y: 10,
draw: function () {
ctx.drawImage(playerImg, this.x, this.y);
//ctx.fillText("Hello World!", this.x, this.y);
},
up: function () {
player.y -= 10;
},
down: function () {
player.y += 10;
},
left: function () {
player.x -= 10;
},
right: function () {
player.x += 10;
}
};
// Event Listeners for Buttons
upButton.addEventListener('click', function () {
player.up();
}, false);
downButton.addEventListener('click', function () {
player.down();
}, false);
leftButton.addEventListener('click', function () {
player.left();
}, false);
rightButton.addEventListener('click', function () {
player.right();
}, false);
/////// note: add player methods to player object
///////////////////////////////////////////////
// Test
function test() {
window.alert("Test 1");
player.x = 10;
player.y = 10;
}
canvas.addEventListener('click', test,...