我有一个名为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)
}
答案 0 :(得分: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();
}
有一些语法问题导致代码甚至执行,以及变量作用域的一些问题。