JS Canvas movement animation loop - javascript

I have an object rendered to a canvas. I'm trying to get the object to move along a set path on a loop. Here is what I have:
// Canvas Element
var canvas = null;
// Canvas Draw
var ctx = null;
// Static Globals
var tileSize = 16,
mapW = 10,
mapH = 10;
// Instances of entities
var entities = [
// A single entity that starts at tile 28, and uses the setPath() function
{
id: 0,
tile: 28,
xy: tileToCoords(28),
width: 16,
height: 24,
speedX: 0,
speedY: 0,
logic: {
func: 'setPath',
// These are the parameters that go into the setPath() function
data: [0, ['down', 'up', 'left', 'right'], tileToCoords(28), 0]
},
dir: {up:false, down:false, left:false, right:false}
}
];
// Array for tile data
var map = [];
window.onload = function(){
// Populate the map array with a blank map and 4 walls
testMap();
canvas = document.getElementById('save');
ctx = canvas.getContext("2d");
// Add all the entities to the map array and start their behavior
for(var i = 0; i < entities.length; ++i){
map[entities[i].tile].render.object = entities[i].id;
if(entities[i].logic){
window[entities[i].logic.func].apply(null, entities[i].logic.data);
}
}
drawGame(map);
window.requestAnimationFrame(function(){
mainLoop();
});
};
function drawGame(map){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// We save all the entity data for later so the background colors don't get rendered on top
var tileObjData = [];
for(var y = 0; y < mapH; ++y){
for(var x = 0; x < mapW; ++x){
var currentPos = ((y*mapW)+x);
ctx.fillStyle = map[currentPos].render.base;
ctx.fillRect(x*tileSize, y*tileSize, tileSize, tileSize);
var thisObj = map[currentPos].render.object;
if(thisObj !== false){
thisObj = entities[thisObj];
var originX = thisObj.xy.x;
var originY = thisObj.xy.y;
tileObjData.push(
{
id: thisObj.id,
originX: originX,
originY: originY,
width: thisObj.width,
height: thisObj.height,
}
);
}
}
}
// Draw all the entities after the background tiles are drawn
for(var i = 0; i < tileObjData.length; ++i){
drawEntity(tileObjData[i].id, tileObjData[i].originX, tileObjData[i].originY, tileObjData[i].width, tileObjData[i].height);
}
}
// Draws the entity data
function drawEntity(id, posX, posY, sizeX, sizeY){
var offX = posX + entities[id].speedX;
var offY = posY + entities[id].speedY;
ctx.fillStyle = '#00F';
ctx.fillRect(offX, offY + sizeX - sizeY, sizeX, sizeY);
entities[id].xy.x = offX;
entities[id].xy.y = offY;
}
// Redraws the canvas with the browser framerate
function mainLoop(){
drawGame(map);
for(var i = 0; i < entities.length; ++i){
animateMove(i, entities[i].dir.up, entities[i].dir.down, entities[i].dir.left, entities[i].dir.right);
}
window.requestAnimationFrame(function(){
mainLoop();
});
}
// Sets the speed, direction, and collision detection of an entity
function animateMove(id, up, down, left, right){
var prevTile = entities[id].tile;
if(up){
var topLeft = {x: entities[id].xy.x, y: entities[id].xy.y};
var topRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y};
if(!map[coordsToTile(topLeft.x, topLeft.y - 1)].state.passable || !map[coordsToTile(topRight.x, topRight.y - 1)].state.passable){
entities[id].speedY = 0;
}
else{
entities[id].speedY = -1;
}
}
else if(down){
var bottomLeft = {x: entities[id].xy.x, y: entities[id].xy.y + entities[id].width - 1};
var bottomRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y + entities[id].width - 1};
if(!map[coordsToTile(bottomLeft.x, bottomLeft.y + 1)].state.passable || !map[coordsToTile(bottomRight.x, bottomRight.y + 1)].state.passable){
entities[id].speedY = 0;
}
else{
entities[id].speedY = 1;
}
}
else{
entities[id].speedY = 0;
}
if(left){
var bottomLeft = {x: entities[id].xy.x, y: entities[id].xy.y + entities[id].width - 1};
var topLeft = {x: entities[id].xy.x, y: entities[id].xy.y};
if(!map[coordsToTile(bottomLeft.x - 1, bottomLeft.y)].state.passable || !map[coordsToTile(topLeft.x - 1, topLeft.y)].state.passable){
entities[id].speedX = 0;
}
else{
entities[id].speedX = -1;
}
}
else if(right){
var bottomRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y + entities[id].width - 1};
var topRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y};
if(!map[coordsToTile(bottomRight.x + 1, bottomRight.y)].state.passable || !map[coordsToTile(topRight.x + 1, topRight.y)].state.passable){
entities[id].speedX = 0;
}
else{
entities[id].speedX = 1;
}
}
else{
entities[id].speedX = 0;
}
entities[id].tile = coordsToTile(entities[id].xy.x + (entities[id].width / 2), entities[id].xy.y + (tileSize / 2));
map[entities[id].tile].render.object = id;
if(prevTile !== entities[id].tile){
map[prevTile].render.object = false;
}
}
//////////////////////////////////////
// THIS IS WHERE I'M HAVING TROUBLE //
//////////////////////////////////////
// A function that can be used by an entity to move along a set path
// id = The id of the entity using this function
// path = An array of strings that determine the direction of movement for a single tile
// originPoint = Coordinates of the previous tile this entity was at. This variable seems to be where problems happen with this logic. It should get reset for every tile length moved, but it only gets reset once currently.
// step = The current index of the path array
function setPath(id, path, originPoint, step){
// Determine if the entity has travelled one tile from the origin
var destX = Math.abs(entities[id].xy.x - originPoint.x);
var destY = Math.abs(entities[id].xy.y - originPoint.y);
if(destX >= tileSize || destY >= tileSize){
// Go to the next step in the path array
step = step + 1;
if(step >= path.length){
step = 0;
}
// Reset the origin to the current tile coordinates
originPoint = entities[id].xy;
}
// Set the direction based on the current index of the path array
switch(path[step]) {
case 'up':
entities[id].dir.up = true;
entities[id].dir.down = false;
entities[id].dir.left = false;
entities[id].dir.right = false;
break;
case 'down':
entities[id].dir.up = false;
entities[id].dir.down = true;
entities[id].dir.left = false;
entities[id].dir.right = false;
break;
case 'left':
entities[id].dir.up = false;
entities[id].dir.down = false;
entities[id].dir.left = true;
entities[id].dir.right = false;
break;
case 'right':
entities[id].dir.up = false;
entities[id].dir.down = false;
entities[id].dir.left = false;
entities[id].dir.right = true;
break;
};
window.requestAnimationFrame(function(){
setPath(id, path, originPoint, step);
});
}
// Take a tile index and return x,y coordinates
function tileToCoords(tile){
var yIndex = Math.floor(tile / mapW);
var xIndex = tile - (yIndex * mapW);
var y = yIndex * tileSize;
var x = xIndex * tileSize;
return {x:x, y:y};
}
// Take x,y coordinates and return a tile index
function coordsToTile(x, y){
var tile = ((Math.floor(y / tileSize)) * mapW) + (Math.floor(x / tileSize));
return tile;
}
// Generate a map array with a blank map and 4 walls
function testMap(){
for(var i = 0; i < (mapH * mapW); ++i){
// Edges
if (
// top
i < mapW ||
// left
(i % mapW) == 0 ||
// right
((i + 1) % mapW) == 0 ||
// bottom
i > ((mapW * mapH) - mapW)
) {
map.push(
{
id: i,
render: {
base: '#D35',
object: false,
sprite: false
},
state: {
passable: false
}
},
);
}
else{
// Grass
map.push(
{
id: i,
render: {
base: '#0C3',
object: false,
sprite: false
},
state: {
passable: true
}
},
);
}
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color: #000;
display: flex;
align-items: center;
justify-content: center;
color: #FFF;
font-size: 18px;
padding: 0;
margin: 0;
}
main{
width: 100%;
max-width: 800px;
margin: 10px auto;
display: flex;
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
}
.game{
width: 1000px;
height: 1000px;
position: relative;
}
canvas{
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
image-rendering: pixelated;
image-rendering: crisp-edges;
}
.game canvas{
position: absolute;
top: 0;
left: 0;
width: 800px;
height: 800px;
}
</style>
</head>
<body>
<main>
<div class="game">
<canvas id="save" width="200" height="200" style="z-index: 1;"></canvas>
</div>
</main>
</body>
</html>
The problem is with the setPath() function, and more specifically I think it's something with the originPoint variable. The idea is that setPath() moves the object one tile per path string, and originPoint should be the coordinates of the last tile visited (so it should only get updated once the object coordinates are one tile length away from the originPoint). Right now it only gets updated the first time and then stops. Hopefully someone can point out what I got wrong here.

Your condition to change the path direction I change it to have conditions for each direction, something like:
if ((entities[id].dir.left && entities[id].xy.x <= tileSize) ||
(entities[id].dir.right && entities[id].xy.x >= tileSize*8) ||
(entities[id].dir.up && entities[id].xy.y <= tileSize) ||
(entities[id].dir.down && entities[id].xy.y >= tileSize*8)) {
and the originPoint was just a reference you should do:
originPoint = JSON.parse(JSON.stringify(entities[id].xy));
See the working code below
// Canvas Element
var canvas = null;
// Canvas Draw
var ctx = null;
// Static Globals
var tileSize = 16,
mapW = 10,
mapH = 10;
// Instances of entities
var entities = [
// A single entity that starts at tile 28, and uses the setPath() function
{
id: 0,
tile: 28,
xy: tileToCoords(28),
width: 16,
height: 24,
speedX: 0,
speedY: 0,
logic: {
func: 'setPath',
// These are the parameters that go into the setPath() function
data: [0, ['down', 'left', 'down', 'left', 'up', 'left', 'left', 'right', 'up', 'right', 'down','right', "up"], tileToCoords(28), 0]
},
dir: {up:false, down:false, left:false, right:false}
}
];
// Array for tile data
var map = [];
window.onload = function(){
// Populate the map array with a blank map and 4 walls
testMap();
canvas = document.getElementById('save');
ctx = canvas.getContext("2d");
// Add all the entities to the map array and start their behavior
for(var i = 0; i < entities.length; ++i){
map[entities[i].tile].render.object = entities[i].id;
if(entities[i].logic){
window[entities[i].logic.func].apply(null, entities[i].logic.data);
}
}
drawGame(map);
window.requestAnimationFrame(function(){
mainLoop();
});
};
function drawGame(map){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// We save all the entity data for later so the background colors don't get rendered on top
var tileObjData = [];
for(var y = 0; y < mapH; ++y){
for(var x = 0; x < mapW; ++x){
var currentPos = ((y*mapW)+x);
ctx.fillStyle = map[currentPos].render.base;
ctx.fillRect(x*tileSize, y*tileSize, tileSize, tileSize);
var thisObj = map[currentPos].render.object;
if(thisObj !== false){
thisObj = entities[thisObj];
var originX = thisObj.xy.x;
var originY = thisObj.xy.y;
tileObjData.push(
{
id: thisObj.id,
originX: originX,
originY: originY,
width: thisObj.width,
height: thisObj.height,
}
);
}
}
}
// Draw all the entities after the background tiles are drawn
for(var i = 0; i < tileObjData.length; ++i){
drawEntity(tileObjData[i].id, tileObjData[i].originX, tileObjData[i].originY, tileObjData[i].width, tileObjData[i].height);
}
}
// Draws the entity data
function drawEntity(id, posX, posY, sizeX, sizeY){
var offX = posX + entities[id].speedX;
var offY = posY + entities[id].speedY;
ctx.fillStyle = '#00F';
ctx.fillRect(offX, offY + sizeX - sizeY, sizeX, sizeY);
entities[id].xy.x = offX;
entities[id].xy.y = offY;
}
// Redraws the canvas with the browser framerate
function mainLoop(){
drawGame(map);
for(var i = 0; i < entities.length; ++i){
animateMove(i, entities[i].dir.up, entities[i].dir.down, entities[i].dir.left, entities[i].dir.right);
}
window.requestAnimationFrame(function(){
mainLoop();
});
}
// Sets the speed, direction, and collision detection of an entity
function animateMove(id, up, down, left, right){
var prevTile = entities[id].tile;
if(up){
var topLeft = {x: entities[id].xy.x, y: entities[id].xy.y};
var topRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y};
if(!map[coordsToTile(topLeft.x, topLeft.y - 1)].state.passable || !map[coordsToTile(topRight.x, topRight.y - 1)].state.passable){
entities[id].speedY = 0;
}
else{
entities[id].speedY = -1;
}
}
else if(down){
var bottomLeft = {x: entities[id].xy.x, y: entities[id].xy.y + entities[id].width - 1};
var bottomRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y + entities[id].width - 1};
if(!map[coordsToTile(bottomLeft.x, bottomLeft.y + 1)].state.passable || !map[coordsToTile(bottomRight.x, bottomRight.y + 1)].state.passable){
entities[id].speedY = 0;
}
else{
entities[id].speedY = 1;
}
}
else{
entities[id].speedY = 0;
}
if(left){
var bottomLeft = {x: entities[id].xy.x, y: entities[id].xy.y + entities[id].width - 1};
var topLeft = {x: entities[id].xy.x, y: entities[id].xy.y};
if(!map[coordsToTile(bottomLeft.x - 1, bottomLeft.y)].state.passable || !map[coordsToTile(topLeft.x - 1, topLeft.y)].state.passable){
entities[id].speedX = 0;
}
else{
entities[id].speedX = -1;
}
}
else if(right){
var bottomRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y + entities[id].width - 1};
var topRight = {x: entities[id].xy.x + entities[id].width - 1, y: entities[id].xy.y};
if(!map[coordsToTile(bottomRight.x + 1, bottomRight.y)].state.passable || !map[coordsToTile(topRight.x + 1, topRight.y)].state.passable){
entities[id].speedX = 0;
}
else{
entities[id].speedX = 1;
}
}
else{
entities[id].speedX = 0;
}
entities[id].tile = coordsToTile(entities[id].xy.x + (entities[id].width / 2), entities[id].xy.y + (tileSize / 2));
map[entities[id].tile].render.object = id;
if(prevTile !== entities[id].tile){
map[prevTile].render.object = false;
}
}
//////////////////////////////////////
// THIS IS WHERE I'M HAVING TROUBLE //
//////////////////////////////////////
// A function that can be used by an entity to move along a set path
// id = The id of the entity using this function
// path = An array of strings that determine the direction of movement for a single tile
// originPoint = Coordinates of the previous tile this entity was at. This variable seems to be where problems happen with this logic. It should get reset for every tile length moved, but it only gets reset once currently.
// step = The current index of the path array
function setPath(id, path, originPoint, step){
if ((entities[id].dir.left && entities[id].xy.x <= originPoint.x - tileSize) ||
(entities[id].dir.right && entities[id].xy.x >= originPoint.x + tileSize) ||
(entities[id].dir.up && entities[id].xy.y <= originPoint.y - tileSize) ||
(entities[id].dir.down && entities[id].xy.y >= originPoint.y + tileSize)) {
// Go to the next step in the path array
step = step + 1;
if(step >= path.length){
step = 0;
}
// Reset the origin to the current tile coordinates
originPoint = JSON.parse(JSON.stringify(entities[id].xy));
}
// Set the direction based on the current index of the path array
switch(path[step]) {
case 'up':
entities[id].dir.up = true;
entities[id].dir.down = false;
entities[id].dir.left = false
entities[id].dir.right = false;
break;
case 'down':
entities[id].dir.up = false;
entities[id].dir.down = true;
entities[id].dir.left = false;
entities[id].dir.right = false;
break;
case 'left':
entities[id].dir.up = false;
entities[id].dir.down = false;
entities[id].dir.left = true;
entities[id].dir.right = false;
break;
case 'right':
entities[id].dir.up = false;
entities[id].dir.down = false;
entities[id].dir.left = false;
entities[id].dir.right = true;
break;
};
window.requestAnimationFrame(function(){
setPath(id, path, originPoint, step);
});
}
// Take a tile index and return x,y coordinates
function tileToCoords(tile){
var yIndex = Math.floor(tile / mapW);
var xIndex = tile - (yIndex * mapW);
var y = yIndex * tileSize;
var x = xIndex * tileSize;
return {x:x, y:y};
}
// Take x,y coordinates and return a tile index
function coordsToTile(x, y){
var tile = ((Math.floor(y / tileSize)) * mapW) + (Math.floor(x / tileSize));
return tile;
}
// Generate a map array with a blank map and 4 walls
function testMap(){
for(var i = 0; i < (mapH * mapW); ++i){
// Edges
if (
// top
i < mapW ||
// left
(i % mapW) == 0 ||
// right
((i + 1) % mapW) == 0 ||
// bottom
i > ((mapW * mapH) - mapW)
) {
map.push(
{
id: i,
render: {
base: '#D35',
object: false,
sprite: false
},
state: {
passable: false
}
},
);
}
else{
// Grass
map.push(
{
id: i,
render: {
base: '#0C3',
object: false,
sprite: false
},
state: {
passable: true
}
},
);
}
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color: #000;
display: flex;
align-items: center;
justify-content: center;
color: #FFF;
font-size: 18px;
padding: 0;
margin: 0;
}
main{
width: 100%;
max-width: 800px;
margin: 10px auto;
display: flex;
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
}
.game{
width: 1000px;
height: 1000px;
position: relative;
}
canvas{
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
image-rendering: pixelated;
image-rendering: crisp-edges;
}
.game canvas{
position: absolute;
top: 0;
left: 0;
width: 800px;
height: 800px;
}
</style>
</head>
<body>
<main>
<div class="game">
<canvas id="save" width="200" height="200" style="z-index: 1;"></canvas>
</div>
</main>
</body>
</html>

As someone has already solved your bug...
This is more than a solution to your problem as the real problem you are facing is complexity, long complex if statements using data structures representing the same information in different ways making it difficult to see simple errors in logic.
On top of that you have some poor style habits that compound the problem.
A quick fix will just mean you will be facing the next problem sooner. You need to write in a ways that reduces the chances of logic errors due to increasing complexity
Style
First style. Good style is very important
Don't assign null to declared variables. JavaScript should not need to use null, the exception to the rule is that some C++ coders infected the DOM API with null returns because they did not understand JavaScipt (or was a cruel joke), and now we are stuck with null
window is the default this (global this) and is seldom needed. Eg window.requestAnimationFrame is identical to just requestAnimationFrame and window.onload is identical to onload
Don't pollute your code with inaccurate, redundant and/or obvious comments, use good naming to provide the needed information. eg:
var map[]; has the comment // array of tile data Well really its an array that has data, who would have guessed, so the comment can be // tiles but then map is a rather ambiguous name. Remove the comment and give the variable a better name.
The comment // Static Globals above some vars. Javascript does not have static as a type so the comment is wrong and the "global's" part is "duh..."
Use const to declare constants, move all the magic numbers to the top and define them as named const. A name has meaning, an number in some code has next to no meaning.
Don't assign listener to the event name, it is unreliable and can be hijacked or overwritten. Always use addEventListener to assign an event listener
Be very careful with your naming. eg the function named coordsToTile is confusing as it does not return a tile, it returns a tile index, either change the function name to match the functions behavior, or change the behavior to match the name.
Don't use redundant intermediate functions, examples:
Your frame request requestAnimationFrame(function(){mainLoop()}); should skip the middle man and be requestAnimationFrame(mainLoop);
You use Function.apply to call the function window[entities[i].logic.func].apply(null, entities[i].logic.data);. apply is used to bind context this to the call, you don't use this in the function so you don't need use the apply. eg window[entities[i].logic.func](...entities[i].logic.data);
BTW being forced to use bracket notation to access a global is a sign of poor data structure. You should never do that.
JavaScript has an unofficial idiomatic styles, you should try to write JS in this style. Some examples from your code
else on the same line as closing }
Space after if, else, for, function() and befor else, opening block {
An id and an index are not the same, use idx or index for an index and id for an identifier
Keep it simple
The more complex you make your data structures the harder it is for you to maintain them.
Structured
Define objects to encapsulate and organize your data.
A global config object, that is transprotable ie can converted be to and from JSON. it contains all the magic numbers, defaults, type descriptions, and what not needed in the game.
Create a set of global utilities that do common repeated tasks, ie create coordinates, list of directions.
Define object that encapsulate the settings and behaviors specific only to that object.
Use polymorphic object design, meaning that different objects use named common behaviors and properties. In the example all drawable object have a function called draw that takes an argument ctx, all objects that can be updated have a function called update
Example
This example is a complete rewrite of your code and fixing your problem. It may be a little advanced, but it is only an example to look though an pick up some tips.
A quick description of the objects used.
Objects
config is transportable config data
testMap is an example map description
tileMap does map related stuff
Path Object encapsulating path logic
Entity Object a single moving entity
Tile Object representing a single tile
game The game state manager
Games have states, eg loading, intro, inPlay, gameOver etc. If you do not plan ahead and create a robust state manager you will find it very difficult to move from one state to the next
I have included the core of a finite state manager. The state manager is responsible for updating and rendering. it is also responsible for all state changes.
setTimeout(() => game.state = "setup", 0); // Will start the game
const canvas = document.getElementById('save');
const ctx = canvas.getContext("2d");
const point = (x = 0, y = 0) => ({x,y});
const dirs = Object.assign(
[point(0, -1), point(1), point(0,1), point(-1)], { // up, right, down, left
"u": 0, // defines index for direction string characters
"r": 1,
"d": 2,
"l": 3,
strToDirIdxs(str) { return str.toLowerCase().split("").map(char => dirs[char]) },
}
);
const config = {
pathIdx: 28,
pathTypes: {
standard: "dulr",
complex: "dulrldudlruldrdlrurdlurd",
},
tile: {size: 16},
defaultTileName: "grass",
entityTypes: {
e: {
speed: 1 / 32, // in fractions of a tile per frame
color: "#00F",
size: {x:16, y:24},
pathName: "standard",
},
f: {
speed: 1 / 16, // in fractions of a tile per frame
color: "#08F",
size: {x:18, y:18},
pathName: "complex",
},
},
tileTypes: {
grass: {
style: {baseColor: "#0C3", object: false, sprite: false},
state: {passable: true}
},
wall: {
style: {baseColor: "#D35", object: false, sprite: false},
state: {passable: false}
},
},
}
const testMap = {
displayChars: {
" " : "grass", // what characters mean
"#" : "wall",
"E" : "grass", // also entity spawn
"F" : "grass", // also entity spawn
},
special: { // spawn enties and what not
"E"(idx) { entities.push(new Entity(config.entityTypes.e, idx)) },
"F"(idx) { entities.push(new Entity(config.entityTypes.f, idx)) }
},
map: // I double the width and ignor every second characters as text editors tend to make chars thinner than high
// 0_1_2_3_4_5_6_7_8_9_ x coord
"####################\n" +
"##FF ## ##\n" +
"## ## ##\n" +
"## #### ##\n" +
"## ##\n" +
"## #### ##\n" +
"## ##\n" +
"## ##\n" +
"## EE##\n" +
"####################",
// 0_1_2_3_4_5_6_7_8_9_ x coord
}
const entities = Object.assign([],{
update() {
for (const entity of entities) { entity.update() }
},
draw(ctx) {
for (const entity of entities) { entity.draw(ctx) }
},
});
const tileMap = {
map: [],
mapToIndex(x, y) { return x + y * tileMap.width },
pxToIndex(x, y) { return x / config.tile.size | 0 + (y / config.tile.size | 0) * tileMap.width },
tileByIdx(idx) { return tileMap.map[idx] },
tileByIdxDir(idx, dir) { return tileMap.map[idx + dir.x + dir.y * tileMap.width] },
idxByDir(dir) { return dir.x + dir.y * tileMap.width },
create(mapConfig) {
tileMap.length = 0;
const rows = mapConfig.map.split("\n");
tileMap.width = rows[0].length / 2 | 0;
tileMap.height = rows.length;
canvas.width = tileMap.width * config.tile.size;
canvas.height = tileMap.height * config.tile.size;
var x, y = 0;
while (y < tileMap.height) {
const row = rows[y];
for (x = 0; x < tileMap.width; x += 1) {
const char = row[x * 2];
tileMap.map.push(new Tile(mapConfig.displayChars[char], x, y));
if (mapConfig.special[char]) {
mapConfig.special[char](tileMap.mapToIndex(x, y));
}
}
y++;
}
},
update () {}, // stub
draw(ctx) {
for (const tile of tileMap.map) { tile.draw(ctx) }
},
};
function Tile(typeName, x, y) {
typeName = config.tileTypes[typeName] ? typeName : config.defaultTileName;
const t = config.tileTypes[typeName];
this.idx = x + y * tileMap.width;
this.coord = point(x * config.tile.size, y * config.tile.size);
this.style = {...t.style};
this.state = {...t.state};
}
Tile.prototype = {
draw(ctx) {
ctx.fillStyle = this.style.baseColor;
ctx.fillRect(this.coord.x, this.coord.y, config.tile.size, config.tile.size);
}
};
function Path(pathName) {
if (typeof config.pathTypes[pathName] === "string") {
config.pathTypes[pathName] = dirs.strToDirIdxs(config.pathTypes[pathName]);
}
this.indexes = config.pathTypes[pathName];
this.current = -1;
}
Path.prototype = {
nextDir(tileIdx) {
var len = this.indexes.length;
while (len--) { // make sure we dont loop forever
const dirIdx = this.indexes[this.current];
if (dirIdx > - 1) {
const canMove = tileMap.tileByIdxDir(tileIdx, dirs[dirIdx]).state.passable;
if (canMove) { return dirs[dirIdx] }
}
this.current = (this.current + 1) % this.indexes.length;
}
}
};
function Entity(type, tileIdx) {
this.coord = point();
this.move = point();
this.color = type.color;
this.speed = type.speed;
this.size = {...type.size};
this.path = new Path(type.pathName);
this.pos = this.nextTileIdx = tileIdx;
this.traveled = 1; // unit dist between tiles 1 forces update to find next direction
}
Entity.prototype = {
set dir(dir) {
if (dir === undefined) { // dont move
this.move.y = this.move.x = 0;
this.nextTileIdx = this.tileIdx;
} else {
this.move.x = dir.x * config.tile.size;
this.move.y = dir.y * config.tile.size;
this.nextTileIdx = this.tileIdx + tileMap.idxByDir(dir);
}
},
set pos(tileIdx) {
this.tileIdx = tileIdx;
const tile = tileMap.map[tileIdx];
this.coord.x = tile.coord.x + config.tile.size / 2;
this.coord.y = tile.coord.y + config.tile.size / 2;
this.traveled = 0;
},
draw(ctx) {
const ox = this.move.x * this.traveled;
const oy = this.move.y * this.traveled;
ctx.fillStyle = this.color;
ctx.fillRect(ox + this.coord.x - this.size.x / 2, oy + this.coord.y - this.size.y / 2, this.size.x, this.size.y)
},
update(){
this.traveled += this.speed;
if (this.traveled >= 1) {
this.pos = this.nextTileIdx;
this.dir = this.path.nextDir(this.tileIdx);
}
}
};
const game = {
currentStateName: undefined,
currentState: undefined,
set state(str) {
if (game.states[str]) {
if (game.currentState && game.currentState.end) { game.currentState.end() }
game.currentStateName = str;
game.currentState = game.states[str];
if (game.currentState.start) { game.currentState.start() }
}
},
states: {
setup: {
start() {
tileMap.create(testMap);
game.state = "play";
},
end() {
requestAnimationFrame(game.render); // start the render loop
delete game.states.setup; // MAKE SURE THIS STATE never happens again
},
},
play: {
render(ctx) {
tileMap.update();
entities.update();
tileMap.draw(ctx);
entities.draw(ctx);
}
}
},
renderTo: ctx,
startTime: undefined,
time: 0,
render(time) {
if (game.startTime === undefined) { game.startTime = time }
game.time = time - game.startTime;
if (game.currentState && game.currentState.render) { game.currentState.render(game.renderTo) }
requestAnimationFrame(game.render);
}
};
body{
background-color: #000;
}
canvas{
image-rendering: pixelated;
position: absolute;
top: 0;
left: 0;
width: 400px;
height: 400px;
}
<canvas id="save" width="200" height="200" style="z-index: 1;"></canvas>
Please Note that there are some running states that have not been tested and as such may have a typo.
Also the tile map must be walled to contain entities or they will throw when they try to leave the playfield.
The code is designed to run in the snippet. To make it work in a standard page add above the very first line setTimeout(() => game.state = "setup", 0); the line addEventListener(load", () = { and after the very last line add the line });

Related

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

Phaser 3 (Game framework): collider callback is called, but somethimes object still passes through other object, instead of colliding

I'm working on a small flappy-bird-like-game demo. Everthing seems fine, but I have a small problem/question.
I setup a collider function, and the callback works as expected, when the "two" objects collide, but there is a strange behavior:
the white-square (the bird) can fly through the obstacles, when coming from the side
but cannot passthrough when coming from below or on above
BUT the callback is execute always.
blue arrow marks where the square passes through
green arrows mark where the square doesn't passthrough
I'm not sure if this is, because I'm using rectangles (they sometimes) cause problems, or because of my nested physics setup. I even tried to replaced the white rectangel with a sprite, but this still produces the same result/error.
For my demo: I could probablly just destroy the object and restart the level on collision, but I still would like to understand why this is happening? And how I can prevent this, inconsistant behavior.
I'm probably missing something, but couldn't find it, and I don't want to rebuild the application again.
So my question is: why is this happening? And How can I prevent this?
Here is the code:
const width = 400;
const height = 200;
const spacing = width / 4;
const levelSpeed = width / 4;
const flySpeed = width / 4;
var GameScene = {
create (){
let player = this.add.rectangle(width / 4, height / 2, 20, 20, 0xffffff);
this.physics.add.existing(player);
this.input.keyboard.on('keydown-SPACE', (event) => {
if(player.body.velocity.y >= -flySpeed/2){
player.body.setVelocityY(-flySpeed);
}
});
player.body.onWorldBounds = true;
player.body.setCollideWorldBounds(true );
this.physics.world.on("worldbounds", function (body) {
console.info('GAME OVER');
player.y = height / 2;
player.body.setVelocity(0);
});
this.pipes = [];
for(let idx = 1; idx <= 10; idx++) {
let obstacle = this.createObstacle(spacing * idx, Phaser.Math.Between(-height/3, 0));
this.add.existing(obstacle);
this.pipes.push(obstacle);
this.physics.add.collider(obstacle.list[0], player)
this.physics.add.collider(obstacle.list[1], player, _ => console.info(2))
}
},
update(){
this.pipes.forEach((item) => {
if(item.x <= 0){
item.body.x = spacing * 10;
}
})
},
extend: {
createObstacle (x, y){
let topPipe = (new Phaser.GameObjects.Rectangle(this, 0, 0 , 20 , height / 2 ,0xff0000)).setOrigin(0);
let bottomPipe = (new Phaser.GameObjects.Rectangle(this, 0, height/2 + 75, 20 , height / 2 ,0xff0000)).setOrigin(0);
this.physics.add.existing(topPipe);
this.physics.add.existing(bottomPipe);
topPipe.body.setImmovable(true);
topPipe.body.allowGravity = false;
bottomPipe.body.setImmovable(true);
bottomPipe.body.allowGravity = false;
let obstacle = new Phaser.GameObjects.Container(this, x, y, [
topPipe,
bottomPipe
]);
this.physics.add.existing(obstacle);
obstacle.body.velocity.x = - levelSpeed;
obstacle.body.allowGravity = false;
return obstacle;
}
}
};
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width,
height,
scene: [GameScene],
physics: {
default: 'arcade',
arcade: {
gravity: { y: flySpeed },
debug: true
},
}
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Currently I just can assume, that the physics objects don't seem to work correct, when physics objects are nested.
Maybe I'm wrong, but since I rewrote the code again without nested physics - objects and it seems to work, I think my assumption Is correct. I shouldn't have tried to over engineer my code.
If someone has more insides, please let me know/share. I still not 100% sure, if this is the real reason, for the strange behavior.
Here the rewriten code:
const width = 400;
const height = 200;
const spacing = width / 4;
const levelSpeed = width / 4;
const flySpeed = width / 4;
var GameScene = {
create (){
let player = this.add.rectangle(width / 4, height / 2, 20, 20, 0xffffff);
this.physics.add.existing(player);
this.input.keyboard.on('keydown-SPACE', (event) => {
if(player.body.velocity.y >= -flySpeed/2){
player.body.setVelocityY(-flySpeed);
}
});
player.body.onWorldBounds = true;
player.body.setCollideWorldBounds(true );
this.physics.world.on("worldbounds", function (body) {
console.info('GAME OVER');
player.x = width / 4;
player.y = height / 2;
player.body.setVelocity(0);
});
this.pipes = [];
for(let idx = 1; idx <= 10; idx++) {
let obstacle = this.createObstacle(spacing * idx, Phaser.Math.Between(-height/3, 0));
this.add.existing(obstacle[0]);
this.add.existing(obstacle[1]);
this.pipes.push(...obstacle);
this.physics.add.collider(obstacle[0], player)
this.physics.add.collider(obstacle[1], player, _ => console.info(2))
}
},
update(){
this.pipes.forEach((item) => {
if(item.x <= 0){
item.body.x = spacing * 10;
}
item.body.velocity.x = - levelSpeed;
})
},
extend: {
createObstacle (x, y){
let topPipe = (new Phaser.GameObjects.Rectangle(this, x, -20 , 20 , height / 2 ,0xff0000)).setOrigin(0);
let bottomPipe = (new Phaser.GameObjects.Rectangle(this, x, height/2 + 75, 20 , height / 2 ,0xff0000)).setOrigin(0);
this.physics.add.existing(topPipe);
this.physics.add.existing(bottomPipe);
topPipe.body.setImmovable(true);
topPipe.body.allowGravity = false;
topPipe.body.velocity.x = - levelSpeed;
bottomPipe.body.setImmovable(true);
bottomPipe.body.allowGravity = false;
bottomPipe.body.velocity.x = - levelSpeed;
return [topPipe, bottomPipe];
}
}
};
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width,
height,
scene: [GameScene],
physics: {
default: 'arcade',
arcade: {
gravity: { y: flySpeed },
debug: true
},
}
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Canvas drawing is very slow

I want to display scale with markings which is working fine. On top of that I also want to display mouse location in the scale with red indicator.
So, I draw canvas when I run the app and then I'm redrawing entire canvas when mouse location is changed.
I'm new to canvas and don't understand whats wrong in my code. I have been trying to resolve it but no luck.
Problem might be in this function,
function drawBlackMarkers(y, coordinateMeasurment){
const markHightY = scaleTextPadding.initial;
ctxLeft.moveTo(coordinateMeasurment, y + markHightY);
ctxLeft.lineTo(completeMarkHight, y + markHightY);
}
I'm having a big for loop means so many iterations to go through and in that loop I call drawBlackMarkers function that many times as shown below.
function setMarkers(initialValY, rangeValY, coordinateMeasurmentr, divisableVal,
scaleCountStartValueOfY, scaleCountRangeValueOfY) {
let count = 0;
// re-modifying scale staring and ending values based on zoom factor
const scaleInceremnt = scaleIncementValue;
for (let y = (initialValY), scaleCountY = scaleCountStartValueOfY;
y <= (rangeValY) && scaleCountY <= scaleCountRangeValueOfY;
y += scaleInceremnt, scaleCountY += incrementFactor) {
switch (count) {
case displayScale.starting:
coordinateMeasurment = marktype.bigMark; count++;
const scaleValY = scaleCountY - divisableVal;
ctxLeft.strokeStyle = colors.black;
ctxLeft.font = scaleNumberFont;
const size = ctxLeft.measureText(scaleValY.toString());
ctxLeft.save();
const textX = coordinateMeasurment + ((size.width) / 2);
const textY = y - scaleTextPadding.alignment;
ctxLeft.translate(textX, textY);
ctxLeft.rotate(-Math.PI / 2);
ctxLeft.translate(-textX, -textY);
ctxLeft.fillText(scaleValY.toString(), coordinateMeasurment, y - scaleTextPadding.complete);
ctxLeft.restore();
break;
case displayScale.middle:
coordinateMeasurment = marktype.middleMark; count++;
break;
case displayScale.end:
coordinateMeasurment = marktype.smallMark; count = 0;
break;
default:
coordinateMeasurment = marktype.smallMark; count++;
break;
}
// to draw scale lines on canvas
// drawBlackMarkers(y, coordinateMeasurment);
}
}
Please check this : http://jsfiddle.net/3v5nt7fe/1/
The problem is if I comment drawBlackMarkers function call, mouse co-ordinate updation is very fast but if I uncomment, it takes so long to update the location.
I really need help to resolve this issue.
It's not the drawBlackMarkers itself, it's this:
for (let y = (initialValY), scaleCountY = scaleCountStartValueOfY;
y <= (rangeValY) && scaleCountY <= scaleCountRangeValueOfY;
y += scaleInceremnt, scaleCountY += incrementFactor) {
This is constantly increasing and happening 640,000 times. You can tell that's the case by writing:
// to draw scale lines on canvas
// drawBlackMarkers(y, coordinateMeasurment);
console.log(y);
and seeing the console result.
So that for loop does very little, because most of it is behind a switch statement, and when it does even this simple drawBlackMarkers outside its showing the true cost of that loop. rangeValY is 640,000, which means the path the canvas context must construct is enormous.
So to fix this you must find a way to ameliorate that problem.
This is doing a lot of unnecessary work
The screen is not 64000 pixels in height. You want to calculate the viewport, and only draw what is in the viewport.
Your function drawBlackMarkers is not the culprit. The system is very slow before that, its simply adding one more thing to be drawn. It was the straw that broke the camel's back.
By reducing the length of what you are drawing, you can very easily avoid the wasted CPU cycles.
In this version, all I have done is re-enable drawBlackMarkers, and shrink the canvas.
const CANVAS_WIDTH = 2000;
const CANVAS_HEIGHT = 50;
const completeMarkHight = 15;
const divisibleValue = 0;
const scaleIncementValue = 10;
const scaleTextPadding = { initial: 0, middle: 5, end: 10, complete: 15, alignment: 18 };
const displayScale = { starting: 0, middle: 5, end: 9 };
const colors = { red: '#FF0000', white: '#D5D6D7', black: '#181c21' };
const marktype = { bigMark: 0, middleMark: 5, smallMark: 10 };
const startingInitialOrigin = { x: 0, y: 0 };
const scaleNumberFont = '10px Titillium Web Regular';
const defaultZoomLevel = 100;
const markingGap = {level1: 400, level2: 200, level3: 100, level4: 50, level5: 20, level6: 10 };
const zoomScaleLevel = {level0: 0, level1: 25, level2: 50, level3: 100, level4: 200, level5: 500, level6: 1000};
var $canvas = $('#canvas');
var ctxLeft = $canvas[0].getContext('2d');
var mousePositionCoordinates;
var pagePositions = { x: 100, y:0 };
var remainderX;
var remainderY;
var scaleCountRemainderX;
var scaleCountRemainderY;
var zoomFactor;
var zoomScale;
var zoomLevel;
var multiplyFactor;
var incrementFactor;
var markingDistance;
var timetaken=0;
ctxLeft.fillStyle = colors.white;
function render() {
clear();
ctxLeft.beginPath();
zoomScale = 1000;
zoomLevel = 1000;
zoomFactor = zoomLevel / defaultZoomLevel;
markingDistance = markingGap.level6;
multiplyFactor = markingDistance / defaultZoomLevel;
incrementFactor = markingDistance / scaleIncementValue;
renderVerticalRuler(startingInitialOrigin.y);
}
function renderVerticalRuler(posY) {
const initialValY = - posY / multiplyFactor;
const rangeValY = (CANVAS_WIDTH - posY) / multiplyFactor;
const initialValOfYwithMultiplyFactor = -posY;
const rangeValOfYwithMultiplyFactor = (CANVAS_WIDTH - posY);
// to adjust scale count get remainder value based on marking gap
scaleCountRemainderY = initialValOfYwithMultiplyFactor % markingDistance;
const scaleCountStartValueOfY = initialValOfYwithMultiplyFactor - scaleCountRemainderY;
const scaleCountRangeValueOfY = rangeValOfYwithMultiplyFactor - scaleCountRemainderY;
// to get orgin(0,0) values
remainderY = initialValY % 100;
const translateY = (posY / multiplyFactor) - remainderY;
ctxLeft.translate(origin.x, translateY); // x,y
const coordinateMeasurment = 0;
const t0 = performance.now();
setMarkers(initialValY, rangeValY, coordinateMeasurment, divisibleValue, scaleCountStartValueOfY, scaleCountRangeValueOfY);
const t1 = performance.now()
console.log("it took " + (t1 - t0) + " milliseconds.");
ctxLeft.stroke();
ctxLeft.closePath();
}
function setMarkers(initialValY, rangeValY, coordinateMeasurmentr, divisableVal,
scaleCountStartValueOfY, scaleCountRangeValueOfY) {
let count = 0;
// re-modifying scale staring and ending values based on zoom factor
const scaleInceremnt = scaleIncementValue;
for (let y = (initialValY), scaleCountY = scaleCountStartValueOfY;
y <= (rangeValY) && scaleCountY <= scaleCountRangeValueOfY;
y += scaleInceremnt, scaleCountY += incrementFactor) {
switch (count) {
case displayScale.starting:
coordinateMeasurment = marktype.bigMark; count++;
const scaleValY = scaleCountY - divisableVal;
ctxLeft.strokeStyle = colors.black;
ctxLeft.font = scaleNumberFont;
const size = ctxLeft.measureText(scaleValY.toString());
ctxLeft.save();
const textX = coordinateMeasurment + ((size.width) / 2);
const textY = y - scaleTextPadding.alignment;
ctxLeft.translate(textX, textY);
ctxLeft.rotate(-Math.PI / 2);
ctxLeft.translate(-textX, -textY);
ctxLeft.fillText(scaleValY.toString(), coordinateMeasurment, y - scaleTextPadding.complete);
ctxLeft.restore();
break;
case displayScale.middle:
coordinateMeasurment = marktype.middleMark; count++;
break;
case displayScale.end:
coordinateMeasurment = marktype.smallMark; count = 0;
break;
default:
coordinateMeasurment = marktype.smallMark; count++;
break;
}
// to draw scale lines on canvas
drawBlackMarkers(y, coordinateMeasurment);
}
}
function drawBlackMarkers(y, coordinateMeasurment){
const markHightY = scaleTextPadding.initial;
ctxLeft.moveTo(coordinateMeasurment, y + markHightY);
ctxLeft.lineTo(completeMarkHight, y + markHightY);
}
function clear() {
ctxLeft.resetTransform();
ctxLeft.clearRect(origin.x, origin.y, CANVAS_HEIGHT, CANVAS_WIDTH);
}
render();
$('.canvas-container').mousemove(function(e) {
mousePositionCoordinates = {x:e.clientX, y:e.clientY};
render();
// SHOW RED INDICATOR
ctxLeft.beginPath();
ctxLeft.strokeStyle = colors.red; // show mouse indicator
ctxLeft.lineWidth = 2;
// to display purple indicator based on zoom level
const mouseX = mousePositionCoordinates.x * zoomFactor;
const mouseY = mousePositionCoordinates.y * zoomFactor;
const markHightY =scaleTextPadding.initial + this.remainderY;
ctxLeft.moveTo(marktype.bigMark, e.clientY );
ctxLeft.lineTo(completeMarkHight, e.clientY);
ctxLeft.stroke();
$('.mouselocation').text(`${mousePositionCoordinates.x},${mousePositionCoordinates.y}`);
});
body, html{
width: 100000px;
height:100000px;
}
.canvas-container{
width:100%;
height:100%;
}
.canvasLeft {
position: absolute;
border:1px solid black;
background: grey;
border-top: none;
z-index: 1;
top:0
}
.mouselocation{
position: fixed;
right: 0px;
top: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="canvas-container">
<canvas id="canvas" class="canvasLeft" width="30" height="2000"></canvas>
</div>
<div class="mouselocation">
</div>

HTML5 Drawing on multiple canvases images don't show up on one of them

Working on a sort of proof-of-concept object-oriented javascript project that emulates a chessboard. Currently I've got four canvases set up, each set to two different boards and two "sidebar" canvases which display the current turn and the list of any pieces taken for the associated game. Here's a screenshot of what it looks like currently:
http://i.imgur.com/GPoVkK2.png
The problem is, the elements within the second sidebar are for whatever reason drawing in the first sidebar, and I haven't been able to figure out why.
Here's all the code files for the project broken out and explained to the best of my ability:
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts/Marker.js"></script>
<script type="text/javascript" src="scripts/TurnMarker.js"></script>
<script type="text/javascript" src="scripts/GameToken.js"></script>
<script type="text/javascript" src="scripts/GameBoard.js"></script>
<script type="text/javascript" src="scripts/Validation.js"></script>
<script type="text/javascript" src="scripts/Main.js"></script>
</head>
<body onLoad=initialize()>
<canvas id="gameBoard" width="400" height="400" style="border:1px solid #000000; position=relative;">
Your browser doesn't support HTML5 canvas.
</canvas>
<canvas id="sideBar" width="50" height="400" style="border:1px solid #000000; position=relative;">
</canvas>
<canvas id="gameBoardWizard" width="400" height="400" style="border:1px solid #000000; position=relative;">
Your browser doesn't support HTML5 canvas.
</canvas>
<canvas id="sideBarWizard" width="50" height="400" style="border:1px solid #000000; position=relative;">
</canvas>
</body>
</html>
Main.js
/*** Chess Board Program
* Author: Alex Jensen
* CS 3160: Concepts of Programming Languages
* 12/5/14
*/
var gameBoards = [];
/** Initialize is called when the page loads (set up in the HTML below)
*
*/
function initialize()
{
createBoard("gameBoard", "sideBar" ,8 , 8);
createBoard("gameBoardWizard", "sideBarWizard" ,8, 8);
// setInterval is a super awesome javascript function and I love it.
setInterval(function() {draw()}, 100);
}
/** CreateBoard is a helper function for Initialize that is responsible for loading a game board into the list of game boards.
* boardID= String title of the HTML5 table within the HTML index file.
*/
function createBoard(boardID, sideBarID, numSquaresRows, numSquaresColumns)
{
var initBoardValidator = [];
for (var i=0;i<numSquaresColumns;i++)
{
initBoardValidator[i] = [];
for (var j=0;j<numSquaresRows;j++)
{
initBoardValidator[i][j] = null;
}
}
var gameBoard = new GameBoard(boardID, sideBarID, numSquaresRows, numSquaresColumns, initBoardValidator, [], []);
gameBoard.tokens = createDefaultTokens(gameBoard);
gameBoard.takenTokens = createDefaultTakeMarkers(gameBoard);
gameBoards[gameBoards.length] = gameBoard;
}
/** Helper function for initialize which creates all the tokens and stores them in appropriate locations.
*
*/
function createDefaultTokens(game)
{
tokens = [];
// Create Pawns
for (var i = 0; i < 8; i++)
{
tokens[tokens.length] = new GameToken(game, "WP", 1, 'images/wp.png', i * game.squareWidth, game.squareHeight, pawnValidator);
tokens[tokens.length] = new GameToken(game, "BP", 2, 'images/bp.png', i * game.squareWidth, game.squareHeight * 6, pawnValidator);
}
// Create other pieces
tokens[tokens.length] = new GameToken(game, "WR", 1, 'images/wr.png', 0, 0, rookValidator);
tokens[tokens.length] = new GameToken(game, "WN", 1, 'images/wn.png', game.squareWidth, 0, knightValidator);
tokens[tokens.length] = new GameToken(game, "WB", 1, 'images/wb.png', game.squareWidth * 2, 0, bishopValidator);
tokens[tokens.length] = new GameToken(game, "WQ", 1, 'images/wq.png', game.squareWidth * 3, 0, queenValidator);
tokens[tokens.length] = new GameToken(game, "WK", 1, 'images/wk.png', game.squareWidth * 4, 0, kingValidator);
tokens[tokens.length] = new GameToken(game, "WB", 1, 'images/wb.png', game.squareWidth * 5, 0, bishopValidator);
tokens[tokens.length] = new GameToken(game, "WN", 1, 'images/wn.png', game.squareWidth * 6, 0, knightValidator);
tokens[tokens.length] = new GameToken(game, "WR", 1, 'images/wr.png', game.squareWidth * 7, 0, rookValidator);
tokens[tokens.length] = new GameToken(game, "BR", 2, 'images/br.png', 0, game.squareWidth * 7, rookValidator);
tokens[tokens.length] = new GameToken(game, "BN", 2, 'images/bn.png', game.squareWidth, game.squareHeight * 7, knightValidator);
tokens[tokens.length] = new GameToken(game, "BB", 2, 'images/bb.png', game.squareWidth * 2, game.squareHeight * 7, bishopValidator);
tokens[tokens.length] = new GameToken(game, "BQ", 2, 'images/bq.png', game.squareWidth * 3, game.squareHeight * 7, queenValidator);
tokens[tokens.length] = new GameToken(game, "BK", 2, 'images/bk.png', game.squareWidth * 4, game.squareHeight * 7, kingValidator);
tokens[tokens.length] = new GameToken(game, "BB", 2, 'images/bb.png', game.squareWidth * 5, game.squareHeight * 7, bishopValidator);
tokens[tokens.length] = new GameToken(game, "BN", 2, 'images/bn.png', game.squareWidth * 6, game.squareHeight * 7, knightValidator);
tokens[tokens.length] = new GameToken(game, "BR", 2, 'images/br.png', game.squareWidth * 7, game.squareHeight * 7, rookValidator);
return tokens;
}
function createDefaultTakeMarkers(game)
{
var takenTokens = [];
// Create Pawns
for (var i = 0; i < 8; i++)
{
takenTokens[takenTokens.length] = new Marker("WP", 1, 'images/wp.png', 5, (i * 20) + 5);
takenTokens[takenTokens.length] = new Marker("BP", 1, 'images/bp.png', 5, game.sideBar.height - ((i * 20) + 25));
}
// Create other pieces
takenTokens[takenTokens.length] = new Marker("WR", 1, 'images/wr.png', 25, 5);
takenTokens[takenTokens.length] = new Marker("WN", 1, 'images/wn.png', 25, 25);
takenTokens[takenTokens.length] = new Marker("WB", 1, 'images/wb.png', 25, 45);
takenTokens[takenTokens.length] = new Marker("WQ", 1, 'images/wq.png', 25, 65);
takenTokens[takenTokens.length] = new Marker("WK", 1, 'images/wk.png', 25, 85);
takenTokens[takenTokens.length] = new Marker("WB", 1, 'images/wb.png', 25, 105);
takenTokens[takenTokens.length] = new Marker("WN", 1, 'images/wn.png', 25, 125);
takenTokens[takenTokens.length] = new Marker("WR", 1, 'images/wr.png', 25, 145);
takenTokens[takenTokens.length] = new Marker("BR", 1, 'images/br.png', 25, game.sideBar.height - 25);
takenTokens[takenTokens.length] = new Marker("BN", 1, 'images/bn.png', 25, game.sideBar.height - 45);
takenTokens[takenTokens.length] = new Marker("BB", 1, 'images/bb.png', 25, game.sideBar.height - 65);
takenTokens[takenTokens.length] = new Marker("BQ", 1, 'images/bq.png', 25, game.sideBar.height - 85);
takenTokens[takenTokens.length] = new Marker("BK", 1, 'images/bk.png', 25, game.sideBar.height - 105);
takenTokens[takenTokens.length] = new Marker("BB", 1, 'images/bb.png', 25, game.sideBar.height - 125);
takenTokens[takenTokens.length] = new Marker("BN", 1, 'images/bn.png', 25, game.sideBar.height - 145);
takenTokens[takenTokens.length] = new Marker("BR", 1, 'images/br.png', 25, game.sideBar.height - 165);
console.log(takenTokens);
return takenTokens;
}
/** Helper function for draw responsible for drawing each gameBoard
*
*/
function draw()
{
for (var i = 0; i < gameBoards.length; i++)
{
gameBoards[i].draw();
}
}
GameBoard.js
function bind(scope, fn) {
return function() {
return fn.apply(scope, arguments);
}
}
function GameBoard(boardID, sideBarID, numSquareRows, numSquareColumns, validator, tokens, takenTokens)
{
this.game = document.getElementById(boardID);
this.gameContext = this.game.getContext("2d");
var gamerect = this.game.getBoundingClientRect();
//this.gameContext.translate(gamerect.left, gamerect.top);
this.sideBar = document.getElementById(sideBarID);
this.sideBarContext = sideBar.getContext("2d");
var siderect = this.sideBar.getBoundingClientRect();
//this.sideBarContext.translate(siderect.left, siderect.top);
this.boardWidth = this.game.width;
this.boardHeight = this.game.height;
this.squareWidth = this.boardWidth / numSquareColumns;
this.squareHeight = this.boardHeight / numSquareRows;
if (this.squareHeight % 1 != 0) alert("WARNING: squareHeight is not a solid number, the program might not work correctly! Always ensure that the board height divided by the number of rows comes out as a whole number.");
if (this.squareWidth % 1 != 0) alert("WARNING: squareWidth is not a solid number, the program might not work correctly! Always ensure that the board width divided by the number of columns comes out as a whole number.");
this.validator = validator;
this.tokens = tokens;
this.takenTokens = takenTokens;
this.turnOrderToken = new TurnMarker('images/wturn.png', 'images/bturn.png', siderect.width / 2 - 20, siderect.height / 2 - 20, 40, 40);
this.activePlayer = 1; // Whose turn is it?
this.selectedToken = null; // What token is currently being dragged around?
this.takePiece = null;
// Event listeners function nearly identically to how they are handled in C#.
this.game.addEventListener("mousedown", bind(this, this.onMouseDown), false);
this.game.addEventListener("mousemove", bind(this, this.onMouseMove), false);
this.game.addEventListener("mouseup", bind(this, this.onMouseUp), false);
/** Helper function for drawBoard responsible for swapping between two colors whenever it is called.
*
*/
this.swapColor = function swapColor()
{
if (this.gameContext.fillStyle != '#0000ff')
{
this.gameContext.fillStyle = '#0000ff';
} else {
this.gameContext.fillStyle = '#ffffff';
}
}
/** Responsible for drawing all the tokens
*
*/
this.drawTokens = function drawTokens()
{
for (var i = 0; i < this.tokens.length; i++)
{
var token = this.tokens[i];
this.gameContext.drawImage(token.image, token.x, token.y, this.squareWidth, this.squareHeight);
}
}
/** Responsible for drawing the checkerboard.
*
*/
this.drawBoard = function drawBoard()
{
this.gameContext.clearRect(0, 0, this.boardWidth, this.boardHeight);
for (var i = 0; i < this.boardWidth; i += this.squareWidth)
{
for (var j = 0; j < this.boardHeight; j += this.squareHeight)
{
this.swapColor();
this.gameContext.fillRect(i,j,this.squareWidth,this.squareHeight);
}
this.swapColor();
}
}
this.drawMarkers = function drawMarkers()
{
for (var i = 0; i < this.takenTokens.length; i++)
{
var marker = this.takenTokens[i];
console.log(marker.image + " " + marker.x + " " + marker.y + " " + marker.width + " " + marker.height);
if (marker.visible)
{
this.sideBarContext.drawImage(marker.image, marker.x, marker.y, marker.width, marker.height);
}
}
}
this.drawTurnMarker = function drawTurnMarker()
{
if (this.activePlayer == 1)
{
console.log(this.turnOrderToken.player1Image + " " + this.turnOrderToken.x + " " + this.turnOrderToken.y + " " + this.turnOrderToken.width + " " + this.turnOrderToken.height);
this.sideBarContext.drawImage(this.turnOrderToken.player1Image, this.turnOrderToken.x, this.turnOrderToken.y, this.turnOrderToken.width, this.turnOrderToken.height);
}
else
{
this.sideBarContext.drawImage(this.turnOrderToken.player2Image, this.turnOrderToken.x, this.turnOrderToken.y, this.turnOrderToken.width, this.turnOrderToken.height);
}
}
/** Container method which runs all draw functions on the board.
*
*/
this.draw = function draw()
{
this.drawBoard();
this.drawTokens();
this.drawMarkers();
this.drawTurnMarker();
}
/** Removes tokens from the board and adds them to the list of captured pieces in the sidebar
*
*/
this.capture = function capture(token)
{
for (var i = 0; i < this.tokens.length; i++)
{
var takenToken = this.tokens[i];
if (takenToken.x == token.x && takenToken.y == token.y)
{
this.tokens.splice(i, 1);
break;
}
}
for (var i = 0; i < this.takenTokens.length; i++)
{
var takenToken = this.takenTokens[i];
if (takenToken.name == token.name && takenToken.visible == false)
{
console.log(takenToken);
takenToken.visible = true;
break;
}
}
}
}
/** Event that fires when the mouse button is released
* Listeners in gameBoard
*/
GameBoard.prototype.onMouseUp = function (event)
{
if (this.selectedToken != null)
{
var gridx = Math.round(this.selectedToken.x / this.squareWidth);
var gridy = Math.round(this.selectedToken.y / this.squareHeight);
// Snap to the nearest tile
this.selectedToken.x = (gridx * this.squareWidth);
this.selectedToken.y = (gridy * this.squareHeight);
// Check to see if the move that was made is legal
this.takePiece = this.validator[gridx][gridy];
if (this.selectedToken.movementValidator())
{
// If it was, then advance the turn
if (this.activePlayer == 1)
{
this.activePlayer = 2;
}
else
{
this.activePlayer = 1;
}
}
else
{
// Otherwise move the token back to where it was
this.selectedToken.x = this.selectedToken.initX;
this.selectedToken.y = this.selectedToken.initY;
}
// Wherever the token ends up, update the grid to reflect that.
this.validator[this.selectedToken.initX / this.squareWidth][this.selectedToken.initY / this.squareHeight] = null;
this.validator[this.selectedToken.x / this.squareWidth][this.selectedToken.y / this.squareHeight] = this.selectedToken;
this.selectedToken = null;
}
}
/**
*
*/
GameBoard.prototype.onMouseDown = function(event)
{
var rect = this.game.getBoundingClientRect();
var mousePos = {x:event.clientX - rect.left, y:event.clientY - rect.top};
for (var i = 0; i < this.tokens.length; i++)
{
token = this.tokens[i];
// if you clicked this token and it's your turn
if (mousePos.x > token.x && mousePos.y > token.y && mousePos.x < token.x + this.squareWidth && mousePos.y < token.y + this.squareHeight && token.player == this.activePlayer)
{
this.selectedToken = token;
// Store where the token was before we picked it up. That way if we make an illegal move we can restore it to its initial location
this.selectedToken.initX = token.x;
this.selectedToken.initY = token.y;
}
}
}
/** Event that fires when the mouse position is updated
* Listeners in gameBoard
*/
GameBoard.prototype.onMouseMove = function(event)
{
if (this.selectedToken != null)
{
var rect = this.game.getBoundingClientRect();
var mousePos = {x:event.clientX - rect.left, y:event.clientY - rect.top};
this.selectedToken.x = mousePos.x - (this.squareWidth / 2);
this.selectedToken.y = mousePos.y - (this.squareHeight / 2);
}
}
Marker.js
/** Marker is a visual widget used to show taken pieces.
* player= The player associated with the marker
* tokenImagePath= The valid path to the location of the marker texture
* x,y= location of marker on the sidebar
*/
function Marker(name, player, markerPath, x, y)
{
this.name = name;
this.image = new Image();
this.x = x;
this.y = y;
this.width = 20;
this.height = 20;
this.player = player;
this.image.src = markerPath;
this.visible = true;
}
GameToken.js
/** GameToken represents a chess piece.
* player= The player the chess piece belongs to
* tokenImagePath= The valid path to the location of the chess piece texture
* x,y= location of token on the board
* movementValidator= Function to determine whether a move made by this token is legal or not.
* Validators are different for different types of tokens.
*/
function GameToken(game, name, player, tokenImagePath, x, y, movementValidator)
{
this.game = game;
this.name = name;
this.image = new Image();
this.x = x;
this.y = y;
game.validator[x / game.squareWidth][y / game.squareHeight] = this;
this.player = player;
this.image.src = tokenImagePath;
this.movementValidator = movementValidator;
}
And finally a WIP Validation script to check for legal moves
/** Specific validation code for Pawns.
*
*/
function pawnValidator()
{
// Pawns are tricky to validate because they can move one square directly forward, but can't take the square directly
// in front of them, and can only move diagonally when they can capture. In addition, they can move two squares
// forward as long as they're in starting position.
if (this.takePiece != null)
{
// If the square we moved to has an enemy in it and we've made a legal move with the pawn to take that piece
if ((this.takePiece.player != this.player &&
(this.x == this.initX + this.squareWidth || this.x == this.initX - this.squareWidth) &&
((this.player == 1 && this.y == this.initY + this.squareHeight) ||
(this.player == 2 && this.y == this.initY - this.squareHeight))))
{
// We're allowed to remove the token here because we've validated that the pawn has made the correct movement to take the piece.
capture(takePiece);
takePiece = null;
return true;
}
else
{
takePiece = null;
return false;
}
}
// The pawn is not capturing, so check to see that the move it is making is legal
else if (this.x == this.initX)
{
if (this.player == 1)
{
if ((this.y == this.initY + this.game.squareHeight) || (this.y == this.initY + (2*this.game.squareHeight)) && this.initY == (this.game.squareHeight))
{
return true;
}
}
else if (this.y == this.initY - this.game.squareHeight || (this.y == this.initY - (2*this.game.squareHeight)) && this.initY == (6*this.game.squareHeight))
{
{
return true;
}
}
}
return false;
}
/** Specific validation code for Rooks.
*
*/
function rookValidator()
{
// First check if the movement made was legal for a rook (straight line)
if (this.x == this.initX || this.y == this.initY)
{
// Next check if the movement made went through any other pieces
if (lineValidation(this.initX, this.initY, this.x, this.y))
{
if (this.game.takePiece != null)
{
this.game.capture(this.game.takePiece);
}
this.game.takePiece = null;
return true;
}
}
return false;
}
/** Specific validation code for Knights.
*
*/
function knightValidator()
{
// First check if the movement made was legal for a knight using relative positioning
var relativeX = Math.abs(this.x - this.initX) / this.game.squareWidth;
var relativeY = Math.abs(this.y - this.initY) / this.game.squareHeight;
if ((relativeX == 1 && relativeY == 2) || (relativeX == 2 && relativeY == 1))
{
// Knights can jump, so we don't need to validate the movement further
if (this.game.takePiece != null)
{
this.game.capture(this.game.takePiece);
}
takePiece = null;
return true;
}
}
/** Specific validation code for Bishops.
*
*/
function bishopValidator()
{
// First check if the movement made was legal for a bishop (diagonal line)
if (Math.abs(this.x - this.initX) == Math.abs(this.y - this.initY))
{
// Next check if the movement made went through any other pieces
if (lineValidation(this.initX, this.initY, this.x, this.y))
{
if (takePiece != null)
{
capture(takePiece);
}
takePiece = null;
return true;
}
}
}
/** Specific validation code for Kings.
*
*/
function kingValidator()
{
// First check if the movement made was legal for a king using relative positioning
var relativeX = Math.abs(this.x - this.initX) / squareSize;
var relativeY = Math.abs(this.y - this.initY) / squareSize;
if ((relativeX == 1 && relativeY == 1) || (relativeX == 1 && relativeY == 0) || (relativeX == 0 && relativeY == 1))
{
// TODO: Check to see if the move puts the king in check. That's a little past the scope of this project but would make for a nice addition.
if (takePiece != null)
{
capture(takePiece);
}
takePiece = null;
return true;
}
}
/** Specific validation code for Queens.
*
*/
function queenValidator()
{
// First check if the movement made was legal for a queen (diagonal line or straight line)
if ((Math.abs(this.x - this.initX) == Math.abs(this.y - this.initY)) ||
(this.x == this.initX || this.y == this.initY))
{
// Next check if the movement made went through any other pieces
if (lineValidation(this.initX, this.initY, this.x, this.y))
{
if (takePiece != null)
{
capture(takePiece);
}
takePiece = null;
return true;
}
}
}
/** Checks each square traveled over a line to see if it has traveled through another piece
* IMPORTANT: This function only works if the move is legal! If the move made is impossible in chess this function
* will not work correctly!
*/
function lineValidation(startX, startY, endX, endY)
{
while (startX != endX || startY != endY)
{
if (startX < endX) startX += squareSize;
if (startY < endY) startY += squareSize;
if (startX > endX) startX -= squareSize;
if (startY > endY) startY -= squareSize;
var checkTake = gameBoardValidator[startX / squareSize][startY / squareSize];
if (checkTake != null && (startX != endX || startY != endY))
{
return false;
}
}
return true;
}
Both games work but the UI elements in that second side canvas always seem to be drawing in the first canvas spot. Anybody see what I goofed up?
In your GameBoard object you are trying to get context from window.sideBar instead of this.sideBar (it should have produced an error in console):
this.sideBarContext = sideBar.getContext("2d");
Change that line to:
this.sideBarContext = this.sideBar.getContext("2d");
^^^^
and it should work.

Why is this index html not displaying the game on my desk top?

I found this game online and am trying to get it to run from my desktop. Is there something special that a person has to do with the URL's or images to make the file recognize were everything is running and located at. I have all of the files and .png files in one folder and on the same level.
I would think that I should see the game on the screen. It is like a left to right horizontal scroll-er with enemy ships that come out of the right side of the screen and the main ship is on the right side of the screen. (Similar to that of the old style defender game)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div id="game-over-overlay"></div>
<div id="game-over">
<h1>GAME OVER</h1>
<button id="play-again">Play Again</button>
</div>
<div class="wrapper">
<div id="instructions">
<div>
move with <span class="key">arrows</span> or <span class="key">wasd</span>
</div>
<div>
shoot with <span class="key">space</span>
</div>
</div>
<div id="score"></div>
</div>
<script type="text/javascript" src="resources.js"></script>
<script type="text/javascript" src="input.js"></script>
<script type="text/javascript" src="sprite.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
sprite.js
(function() {
function Sprite(url, pos, size, speed, frames, dir, once) {
this.pos = pos;
this.size = size;
this.speed = typeof speed === 'number' ? speed : 0;
this.frames = frames;
this._index = 0;
this.url = url;
this.dir = dir || 'horizontal';
this.once = once;
};
Sprite.prototype = {
update: function(dt) {
this._index += this.speed*dt;
},
render: function(ctx) {
var frame;
if(this.speed > 0) {
var max = this.frames.length;
var idx = Math.floor(this._index);
frame = this.frames[idx % max];
if(this.once && idx >= max) {
this.done = true;
return;
}
}
else {
frame = 0;
}
var x = this.pos[0];
var y = this.pos[1];
if(this.dir == 'vertical') {
y += frame * this.size[1];
}
else {
x += frame * this.size[0];
}
ctx.drawImage(resources.get(this.url),
x, y,
this.size[0], this.size[1],
0, 0,
this.size[0], this.size[1]);
}
};
window.Sprite = Sprite;
resources.js
(function() {
var resourceCache = {};
var loading = [];
var readyCallbacks = [];
// Load an image url or an array of image urls
function load(urlOrArr) {
if(urlOrArr instanceof Array) {
urlOrArr.forEach(function(url) {
_load(url);
});
}
else {
_load(urlOrArr);
}
}
function _load(url) {
if(resourceCache[url]) {
return resourceCache[url];
}
else {
var img = new Image();
img.onload = function() {
resourceCache[url] = img;
if(isReady()) {
readyCallbacks.forEach(function(func) { func(); });
}
};
resourceCache[url] = false;
img.src = url;
}
}
function get(url) {
return resourceCache[url];
}
function isReady() {
var ready = true;
for(var k in resourceCache) {
if(resourceCache.hasOwnProperty(k) &&
!resourceCache[k]) {
ready = false;
}
}
return ready;
}
function onReady(func) {
readyCallbacks.push(func);
}
window.resources = {
load: load,
get: get,
onReady: onReady,
isReady: isReady
};
input.js
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
apps.js
// A cross-browser requestAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = (now - lastTime) / 1000.0;
update(dt);
render();
lastTime = now;
requestAnimFrame(main);
};
function init() {
terrainPattern = ctx.createPattern(resources.get('terrain.png'), 'repeat');
document.getElementById('play-again').addEventListener('click', function() {
reset();
});
reset();
lastTime = Date.now();
main();
}
resources.load([
'sprites.png',
'terrain.png'
]);
resources.onReady(init);
// Game state
var player = {
pos: [0, 0],
sprite: new Sprite('sprites.png', [0, 0], [39, 39], 16, [0, 1])
};
var bullets = [];
var enemies = [];
var explosions = [];
var lastFire = Date.now();
var gameTime = 0;
var isGameOver;
var terrainPattern;
var score = 0;
var scoreEl = document.getElementById('score');
// Speed in pixels per second
var playerSpeed = 200;
var bulletSpeed = 500;
var enemySpeed = 100;
// Update game objects
function update(dt) {
gameTime += dt;
handleInput(dt);
updateEntities(dt);
// It gets harder over time by adding enemies using this
// equation: 1-.993^gameTime
if(Math.random() < 1 - Math.pow(.993, gameTime)) {
enemies.push({
pos: [canvas.width,
Math.random() * (canvas.height - 39)],
sprite: new Sprite('sprites.png', [0, 78], [80, 39],
6, [0, 1, 2, 3, 2, 1])
});
}
checkCollisions();
scoreEl.innerHTML = score;
};
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
if(input.isDown('SPACE') && !isGameOver && Date.now() - lastFire > 100) {
var x = player.pos[0] + player.sprite.size[0] / 2;
var y = player.pos[1] + player.sprite.size[1] / 2;
bullets.push({ pos: [x, y],
dir: 'forward',
sprite: new Sprite('sprites.png', [0, 39], [18, 8]) });
bullets.push({ pos: [x, y],
dir: 'up',
sprite: new Sprite('sprites.png', [0, 50], [9, 5]) });
bullets.push({ pos: [x, y],
dir: 'down',
sprite: new Sprite('sprites.png', [0, 60], [9, 5]) });
lastFire = Date.now();
}
}
function updateEntities(dt) {
// Update the player sprite animation
player.sprite.update(dt);
// Update all the bullets
for(var i=0; i<bullets.length; i++) {
var bullet = bullets[i];
switch(bullet.dir) {
case 'up': bullet.pos[1] -= bulletSpeed * dt; break;
case 'down': bullet.pos[1] += bulletSpeed * dt; break;
default:
bullet.pos[0] += bulletSpeed * dt;
}
// Remove the bullet if it goes offscreen
if(bullet.pos[1] < 0 || bullet.pos[1] > canvas.height ||
bullet.pos[0] > canvas.width) {
bullets.splice(i, 1);
i--;
}
}
// Update all the enemies
for(var i=0; i<enemies.length; i++) {
enemies[i].pos[0] -= enemySpeed * dt;
enemies[i].sprite.update(dt);
// Remove if offscreen
if(enemies[i].pos[0] + enemies[i].sprite.size[0] < 0) {
enemies.splice(i, 1);
i--;
}
}
// Update all the explosions
for(var i=0; i<explosions.length; i++) {
explosions[i].sprite.update(dt);
// Remove if animation is done
if(explosions[i].sprite.done) {
explosions.splice(i, 1);
i--;
}
}
}
// Collisions
function collides(x, y, r, b, x2, y2, r2, b2) {
return !(r <= x2 || x > r2 ||
b <= y2 || y > b2);
}
function boxCollides(pos, size, pos2, size2) {
return collides(pos[0], pos[1],
pos[0] + size[0], pos[1] + size[1],
pos2[0], pos2[1],
pos2[0] + size2[0], pos2[1] + size2[1]);
}
function checkCollisions() {
checkPlayerBounds();
// Run collision detection for all enemies and bullets
for(var i=0; i<enemies.length; i++) {
var pos = enemies[i].pos;
var size = enemies[i].sprite.size;
for(var j=0; j<bullets.length; j++) {
var pos2 = bullets[j].pos;
var size2 = bullets[j].sprite.size;
if(boxCollides(pos, size, pos2, size2)) {
// Remove the enemy
enemies.splice(i, 1);
i--;
// Add score
score += 100;
// Add an explosion
explosions.push({
pos: pos,
sprite: new Sprite('sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
// Remove the bullet and stop this iteration
bullets.splice(j, 1);
break;
}
}
if(boxCollides(pos, size, player.pos, player.sprite.size)) {
gameOver();
}
}
}
function checkPlayerBounds() {
// Check bounds
if(player.pos[0] < 0) {
player.pos[0] = 0;
}
else if(player.pos[0] > canvas.width - player.sprite.size[0]) {
player.pos[0] = canvas.width - player.sprite.size[0];
}
if(player.pos[1] < 0) {
player.pos[1] = 0;
}
else if(player.pos[1] > canvas.height - player.sprite.size[1]) {
player.pos[1] = canvas.height - player.sprite.size[1];
}
}
// Draw everything
function render() {
ctx.fillStyle = terrainPattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Render the player if the game isn't over
if(!isGameOver) {
renderEntity(player);
}
renderEntities(bullets);
renderEntities(enemies);
renderEntities(explosions);
};
function renderEntities(list) {
for(var i=0; i<list.length; i++) {
renderEntity(list[i]);
}
}
function renderEntity(entity) {
ctx.save();
ctx.translate(entity.pos[0], entity.pos[1]);
entity.sprite.render(ctx);
ctx.restore();
}
// Game over
function gameOver() {
document.getElementById('game-over').style.display = 'block';
document.getElementById('game-over-overlay').style.display = 'block';
isGameOver = true;
}
// Reset game to original state
function reset() {
document.getElementById('game-over').style.display = 'none';
document.getElementById('game-over-overlay').style.display = 'none';
isGameOver = false;
gameTime = 0;
score = 0;
enemies = [];
bullets = [];
player.pos = [50, canvas.height / 2];
app.css
html, body {
margin: 0;
padding: 0;
background-color: #151515;
}
canvas {
display: block;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper {
width: 512px;
margin: 0 auto;
margin-top: 2em;
}
#instructions {
float: left;
font-family: sans-serif;
color: #757575;
}
#score {
float: right;
color: white;
font-size: 2em;
}
.key {
color: #aaffdd;
}
#game-over, #game-over-overlay {
margin: auto;
width: 512px;
height: 480px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#game-over-overlay {
background-color: black;
opacity: .5;
}
#game-over {
height: 200px;
text-align: center;
color: white;
}
#game-over h1 {
font-size: 3em;
font-family: sans-serif;
}
#game-over button {
font-size: 1.5em;
}
Here is the original game link
http://jlongster.com/Making-Sprite-based-Games-with-Canvas
If someone could put up a fiddle to see why it is not working it would be most appreciated.
Errors from the console
Uncaught SyntaxError: Unexpected end of input resources.js:61
Uncaught SyntaxError: Unexpected end of input input.js:43
Uncaught SyntaxError: Unexpected end of input sprite.js:54
Uncaught SyntaxError: Unexpected end of input app.js:302
Are you running this on a webserver? The way that you phrased it makes me think you you downloaded those files and just double-clicked index.html.
You need to download something like https://www.apachefriends.org/index.html and start the Apache service up, then put your files in the /xampp/htdocs/ folder... then goto
http://localhost/index.html
to get it to load.

Categories