一个简易的渲染循环结构

上代码:

<!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>Micro Renderer</title>
</head>

<body>
  <span id="tips"></span>
  <hr>
  <button onclick="init()">Start Render</button>
  <script>
    function startRender(renderer) {
      const layer = renderer.layer
      function render(time) {
        layer.render(time)
        requestAnimationFrame(render)
      }

      requestAnimationFrame(render)
    }

    class Layer {
      constructor(dom) {
        this.dom = dom
      }
      render(time) {
        this.dom.innerHTML = `Time cost: ${time}`
      }
    }
    class Renderer {
      constructor(layer) {
        this.layer = layer
      }

      beginRender() {
        startRender(this)
      }
    }

    function init() {
      const layer = new Layer(document.getElementById('tips'))
      const renderer = new Renderer(layer)
      renderer.beginRender()
    }
  </script>
</body>

</html>

不需要HTTP环境,双击用浏览器打开,点击按钮即可看到不停跳动的数字

结构

各部分含义

posted @ 2021-04-01 09:20  岭南灯火  阅读(168)  评论(0编辑  收藏  举报