1

I have created a game on my webpage using HTML 5 canvas and javascript.. the game runs in a loop and the user can play this using the keyboard. The game canvas on the webpage has an ID ="gamecanvas".

However, when the view port size decreases, I want to STOP the game and replace this with an animation (the game does not play well on a small screen size)

To achieve this I want to swop the ID attribute of the game canvas FROM ID ="gamecanvas" TO ID= ="animationcanvas".

This will ensure that my animation Javascript file will access the canavs (as opposed to the game Javascript file).

Is this POSSIBLE using Jquery and will this eventually crash the browser as two scripts are lopping and running ?

Can someone help me complete the function below?

// HTML 5 canvas element

   <canvas id="gamecanvas" width="800" height="380"></canvas> 

// switch ID code

$(document).ready(function() {
var $window = $(window);

function checkWidth() {
    var windowsize = $window.width();
    if (windowsize < 979) {
        ...... Change ID
    }  
    else {  
        Change Id... 
    } 
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});

Many thanks

stckpete
  • 571
  • 1
  • 4
  • 13

1 Answers1

0

To switch the ID: jsBin demo

$(document).ready(function() {
    var $window = $(window);
    var $canvas = $("canvas");

    function checkWidth() {
       $canvas.attr("id", $window.width()<979 ? "animationcanvas" : "gamecanvas");
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $window.resize(checkWidth);
});

See also: https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame to cancel an ongoing game loop.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313