0

I would like to be able to render multiple games from different javaScript files in the same canvas element, alternating them with the press of a button/key. I have done this before but writing all the code in one script. The easiest way would be for every script to rely on a global variable number and draw when their number is called.

For example:

  if(pnum === 0){

    //Draw the page colour
        ctx.fillStyle = pcolour[pnum];
        ctx.fillRect(0,0, w,h);

    ctx.fillStyle = pcolour[1];
    ctx.fillText("Wubbalubbadubdub", 100,100);

    }else ctx.clearRect(0,0,w,h);

and:

    if(pnum === 1){

    ctx.fillStyle = pcolour[pnum];
    ctx.fillRect(0,0, w, h);

    ctx.fillStyle = pcolour[0];
    ctx.fillText("It happened", 100,100);



    }else ctx.clearRect(0,0,w,h);

Where:

var pnum = 0;
var pcolour = [
    "red",
    "blue"
    ];
Aziz
  • 7,685
  • 3
  • 31
  • 54
Etc_Null
  • 11
  • 2
  • Okay, so... what's the question? Are you stuck on some part of implementing this, and if so, what is the code causing a problem? – user812786 Sep 18 '15 at 14:51
  • I want to have 2 canvas' that draw on the same html doc, and only when their number is called. – Etc_Null Sep 23 '15 at 14:59
  • I mean, your idea of a global variable used in an if statement to select which game seems reasonable, so I'm not sure from your question what part you need help with? If it's the global variable part, you can write a main script which could set the variable, and then include multiple JS scripts which can check the value of it. ([This question](http://stackoverflow.com/questions/2932782/global-variables-in-javascript-across-multiple-files) might be helpful.) – user812786 Sep 23 '15 at 15:13
  • Based on your description, though, I'd structure the main script more like: `if (globalVar === 1) { game1(); } else if (globalVar === 2) { game2(); }`, where `game1()` and `game2()` are the main functions in whatever your game scripts are. – user812786 Sep 23 '15 at 15:14

0 Answers0