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


working on sort of proof-of-concept object-oriented javascript project emulates chessboard. i've got 4 canvases set up, each set 2 different boards , 2 "sidebar" canvases display current turn , list of pieces taken associated game. here's screenshot of looks currently:

http://i.imgur.com/gpovkk2.png

the problem is, elements within second sidebar whatever reason drawing in first sidebar, , haven't been able figure out why.

here's code files project broken out , explained best of 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;"> 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;"> 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 called when page loads (set in html below) *   */ function initialize() {     createboard("gameboard", "sidebar" ,8 , 8);     createboard("gameboardwizard", "sidebarwizard" ,8, 8);     // setinterval super awesome javascript function , love it.     setinterval(function() {draw()}, 100); }  /** createboard helper function initialize responsible loading game board list of game boards. *   boardid= string title of html5 table within html index file. */ function createboard(boardid, sidebarid, numsquaresrows, numsquarescolumns) {     var initboardvalidator = [];     (var i=0;i<numsquarescolumns;i++)      {         initboardvalidator[i] = [];         (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 initialize creates tokens , stores them in appropriate locations. * */ function createdefaulttokens(game) {     tokens = [];     // create pawns     (var = 0; < 8; i++)     {         tokens[tokens.length] = new gametoken(game, "wp", 1, 'images/wp.png', * game.squarewidth, game.squareheight, pawnvalidator);         tokens[tokens.length] = new gametoken(game, "bp", 2, 'images/bp.png', * 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     (var = 0; < 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 draw responsible drawing each gameboard  *  */ function draw() {     (var = 0; < 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 not solid number, program might not work correctly! ensure board height divided number of rows comes out whole number.");     if (this.squarewidth % 1 != 0) alert("warning: squarewidth not solid number, program might not work correctly! ensure board width divided number of columns comes out 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; // turn it?     this.selectedtoken = null; // token being dragged around?     this.takepiece = null;       // event listeners function identically how 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 drawboard responsible swapping between 2 colors whenever called.     *     */     this.swapcolor = function swapcolor()     {         if (this.gamecontext.fillstyle != '#0000ff')         {             this.gamecontext.fillstyle = '#0000ff';         } else {             this.gamecontext.fillstyle = '#ffffff';         }     }      /** responsible drawing tokens     *     */     this.drawtokens = function drawtokens()     {         (var = 0; < this.tokens.length; i++)         {             var token = this.tokens[i];             this.gamecontext.drawimage(token.image, token.x, token.y, this.squarewidth, this.squareheight);         }     }      /** responsible drawing checkerboard.     *     */     this.drawboard = function drawboard()     {         this.gamecontext.clearrect(0, 0, this.boardwidth, this.boardheight);         (var = 0; < this.boardwidth; += this.squarewidth)          {             (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()     {         (var = 0; < 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 runs draw functions on board.      *      */     this.draw = function draw()     {         this.drawboard();         this.drawtokens();         this.drawmarkers();         this.drawturnmarker();     }      /** removes tokens board , adds them list of captured pieces in sidebar     *     */     this.capture = function capture(token)     {         (var  = 0; < this.tokens.length; i++)         {             var takentoken = this.tokens[i];             if (takentoken.x == token.x && takentoken.y == token.y)             {                 this.tokens.splice(i, 1);                 break;             }         }         (var  = 0; < 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 fires when mouse button 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 nearest tile         this.selectedtoken.x = (gridx * this.squarewidth);         this.selectedtoken.y = (gridy * this.squareheight);          // check see if move made legal         this.takepiece = this.validator[gridx][gridy];         if (this.selectedtoken.movementvalidator())         {             // if was, advance turn             if (this.activeplayer == 1)             {                 this.activeplayer = 2;             }              else              {                 this.activeplayer = 1;             }         }          else          {             // otherwise move token             this.selectedtoken.x = this.selectedtoken.initx;             this.selectedtoken.y = this.selectedtoken.inity;         }          // wherever token ends up, update grid 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};     (var = 0; < this.tokens.length; i++)     {         token = this.tokens[i];         // if clicked token , it's 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 token before picked up. way if make illegal move can restore initial location             this.selectedtoken.initx = token.x;             this.selectedtoken.inity = token.y;         }     } }  /** event fires when mouse position 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 visual widget used show taken pieces.  *  player= player associated marker *  tokenimagepath= valid path location of marker texture *  x,y= location of marker on 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 chess piece.  *  player= player chess piece belongs *  tokenimagepath= valid path location of chess piece texture *  x,y= location of token on board *  movementvalidator= function determine whether move made token legal or not.  *  validators different 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 wip validation script check legal moves

/** specific validation code pawns. * */ function pawnvalidator() {     // pawns tricky validate because can move 1 square directly forward, can't take square directly     // in front of them, , can move diagonally when can capture. in addition, can move 2 squares      // forward long they're in starting position.     if (this.takepiece != null)     {         // if square moved has enemy in , we've made legal move pawn take 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 remove token here because we've validated pawn has made correct movement take piece.             capture(takepiece);             takepiece = null;             return true;         }         else         {             takepiece = null;             return false;         }     }     // pawn not capturing, check see move making 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 rooks. * */ function rookvalidator() {     // first check if movement made legal rook (straight line)     if (this.x == this.initx || this.y == this.inity)     {     // next check if movement made went through 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 knights. * */ function knightvalidator() {     // first check if movement made legal 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, don't need validate movement further         if (this.game.takepiece != null)          {             this.game.capture(this.game.takepiece);         }         takepiece = null;         return true;     } }  /** specific validation code bishops. * */ function bishopvalidator() {     // first check if movement made legal bishop (diagonal line)     if (math.abs(this.x - this.initx) == math.abs(this.y - this.inity))     {         // next check if movement made went through other pieces         if (linevalidation(this.initx, this.inity, this.x, this.y))         {             if (takepiece != null)              {                 capture(takepiece);             }             takepiece = null;             return true;         }     } }  /** specific validation code kings. * */ function kingvalidator() {     // first check if movement made legal 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 see if move puts king in check. that's little past scope of project make nice addition.         if (takepiece != null)          {             capture(takepiece);         }         takepiece = null;         return true;     } }  /** specific validation code queens. * */ function queenvalidator() {     // first check if movement made legal 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 movement made went through 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 on line see if has traveled through piece *  important: function works if move legal! if move made impossible in chess function *  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 ui elements in second side canvas seem drawing in first canvas spot. see goofed up?

in gameboard object trying context window.sidebar instead of this.sidebar (it should have produced error in console):

this.sidebarcontext = sidebar.getcontext("2d"); 

change line to:

this.sidebarcontext = this.sidebar.getcontext("2d");                       ^^^^ 

and should work.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -