简体   繁体   中英

how to pause a html5 canvas javascript animation with a keyboard input

I have a function called drawArc which is animated but I need to be able to pause and unpause with a keyboard input I though I knew how but when I tried this nothing happened. any help would be appreciated. thanks.

if(window.addEventListener) 
{
window.addEventListener 
( 'load', onLoad, false);
window.addEventListener
('keydown',onKeyDown, false);
}

function onKeyDown(event) 
{ 
var keyCode = event.keyCode;
switch(keyCode) 
{ 
    case 80: //p
    togglePause();
    break; 
}
}

function togglePause() 
{
    if (!Paused) 
    {
        clearInterval(drawArc);
        Paused = true;
    } 
    else if (Paused) 
    {
        setInterval(drawArc, time);
        Paused = false;
    }
}

function onLoad() 
{ 
    var canvas; 
    var context;
    var angle = 0;
    var time= 20;
    var paused = true;

function initialise() 
{
    canvas = document.getElementById('canvas'); 

    if (!canvas) 
    { 
        alert('Error: I cannot find the canvas element!'); 
        return; 
    }

    if (!canvas.getContext) 
    { 
        alert('Error: no canvas.getContext!'); 
        return; 
    }

    context = canvas.getContext('2d'); 
    if (!context) 
    { 
        alert('Error: failed to getContext!'); 
        return; 
    }

return setInterval(drawArc, time)

}

Try this: http://jsbin.com/udebiv/2/edit

var canvas
  , context
  , angle = 0
  , time= 20
  , paused = false
  , timer;

if (window.addEventListener) {
  window.addEventListener( 'load', initialise, false);
  window.addEventListener('keydown',onKeyDown, false);
}

function onKeyDown(event) { 
  var keyCode = event.keyCode;
  switch(keyCode){ 
    case 80: //p
      togglePause();
      break; 
  }
}

function togglePause() {
  if (!paused){
    clearInterval(timer);
    paused = true;
  } else {
    timer = setInterval(drawArc, time);
    paused = false;
  }
}

function initialise() {
  canvas = document.getElementById('canvas'); 

  if (!canvas){ 
    alert('Error: I cannot find the canvas element!'); 
    return; 
  }

  if (!canvas.getContext){ 
    alert('Error: no canvas.getContext!'); 
    return; 
  }

  context = canvas.getContext('2d'); 
  if (!context){ 
    alert('Error: failed to getContext!'); 
    return; 
  }

  timer = setInterval(drawArc, time)
}

function drawArc(){
  // do your drawing here
  // I'm just setting body text so you can see togglePause working
  document.body.innerHTML = Math.random();
}

There were a few syntax problems that were causing your code from even executing, as well as some issues with variable scoping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM