0

我有一个名为 drawArc 的函数,它是动画的,但我需要能够通过键盘输入来暂停和取消暂停,虽然我知道怎么做,但是当我尝试这个时,什么也没发生。任何帮助,将不胜感激。谢谢。

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)

}
4

1 回答 1

2

试试这个: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();
}

有一些语法问题导致您的代码甚至无法执行,以及变量范围的一些问题。

于 2012-12-07T00:30:17.410 回答