计算FPS,以及同时按下键盘事件,鼠标事件

-

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<div id="fpsdom"></div>
<button onclick="start()">开始</button>
<button onclick="end()">结束</button>
<script>
  var pwgl = {
    currrentTime: undefined,
    lastTime:undefined,
    fpsNum:0,
    fpsins: null
  }
  function tick(){
    pwgl.currrentTime = Date.now();
    if(pwgl.lastTime === undefined) {
      pwgl.lastTime = Date.now();
    }
    if(pwgl.currrentTime - pwgl.lastTime >= 1000) {
      fpsdom.innerHTML = pwgl.fpsNum;
      pwgl.fpsNum = 0;
      pwgl.lastTime = pwgl.currrentTime;
    }
    pwgl.fpsNum++;
    pwgl.fpsins = requestAnimationFrame(tick);
  }
  function start(){
    if(pwgl.fpsins === null) {
      tick();
    }
  }
  function end(){
    cancelAnimationFrame(pwgl.fpsins);
    pwgl.fpsins = null;
    pwgl.lastTime = undefined;
    pwgl.fpsNum = 0;
  }

  // 键盘按下事件以及同时按下事件
  // 同时按下键盘事件的原理时,在keydown时,将keycode在映射中设置为true,在keypress中判断同时案中事件,在keyup将映射的keycode设置为false
  var o = {};
  document.addEventListener('keydown', handleKeydown, false);
  document.addEventListener('keyup', handleKeyup, false);
  document.addEventListener('keypress', handleKeypress, false);
  function handleKeydown(event){
    console.log('keydown - keyCode=%d, charCode=%d, 是什么:%s', event.keyCode, event.charCode, String.fromCharCode(event.keyCode));
    o[event.keyCode] = true;
  }
  function handleKeyup(event){
    console.log('keyup - keyCode=%d, charCode=%d, 是什么:%s', event.keyCode, event.charCode, String.fromCharCode(event.keyCode));
    o[event.keyCode] = false;
  }
  function handleKeypress(event){
    console.log('keypress - keyCode=%d, charCode=%d, 是什么:%s', event.keyCode, event.charCode, String.fromCharCode(event.keyCode));
    if(o[65] && o[83]) {
      console.log('同时按了A+S')
    }
  }

  // 鼠标事件
  document.addEventListener('mousedown', handleMouseDown, false);
  document.addEventListener('mousemove', handleMouseMove, false);
  document.addEventListener('mouseup', handleMouseUp, false);
  function handleMouseDown(event){
    console.log('mousedown - clientX=%d, clientY=%d, button=%d', event.clientX, event.clientY, event.button);
  }
  function handleMouseMove(event){
    console.log('mousemove - clientX=%d, clientY=%d, button=%d', event.clientX, event.clientY, event.button);
  }
  function handleMouseUp(event){
    console.log('mouseup - clientX=%d, clientY=%d, button=%d', event.clientX, event.clientY, event.button);
  }
</script>
</body>
</html>

 

 

 

 

 

 

 

 

-

posted @ 2024-06-14 22:23  古墩古墩  Views(6)  Comments(0Edit  收藏  举报