2

I want to implement the following logic (this may sound strange, but to me it feels like a decent idea).

Several months ago I asked this question, and the solution with pixelRatio still seems quite ok. But iPhones and some Android devices have much better performance than mine, so I want to let them render my scene in a better quality. The idea is, I want an adaptive pixelRatio: determine the current FPS, and if it is low enough, re-render the scene again with a lower pixelRatio.

I'm not using requestAnimationFrame explicitly anywhere in the project, so I cannot obviously use this approach. I was wondering if Konva had any API for this purpose - or some hooks/events I could attach to in order to measure FPS.

Or maybe this is a bad idea and I should give up on it?

Mikhail Dudin
  • 459
  • 5
  • 15

2 Answers2

2

Konva itself doesn't have direct API to get current FPS. But you can use timeDiff argument from Konva.Animation to understand the current FPS. fps = 1000 / timeDiff.

const anim = new Konva.Animation(f => {
  if (f.timeDiff > 60) {
    // time for frame is too big, decrease quality
    if (layer.getCanvas().getPixelRatio() > 1) {
      layer.getCanvas().setPixelRatio(0.2);
    }
  } else {
    // time for frame is too small, increase quality
    if (layer.getCanvas().getPixelRatio() < 1) {
      layer.getCanvas().setPixelRatio(2);
    }
  }
}, [layer]);

Demo: https://jsbin.com/regacabogo/3/edit?html,js,output

timeDiff is not consistent per frame. And may jump a lot, so you may need to write a "smoothing" algorithms. For example, change quality only if FPS is too low/high for many frames in a row.

Also, you can use requestAnimationFrame API to calculate FPS manually.

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
lavrton
  • 18,973
  • 4
  • 30
  • 63
1

Konva has an example with an FPS counter, using stats.js

See https://konvajs.org/docs/sandbox/Jumping_Bunnies.html for the original

Minimum example:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/konva@8.3.14/konva.min.js"></script>
    <meta charset="utf-8" />
    <title>Konva Fps Demo</title>
  </head>

  <body>
    <div id="container"></div>
    <script src="https://mrdoob.github.io/stats.js/build/stats.min.js"></script>
    <script defer="defer">
      var width = window.innerWidth;
      var height = window.innerHeight;

      var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height,
      });
      var layer = new Konva.FastLayer();
      stage.add(layer);

      var stats = new Stats();
      document.body.appendChild(stats.domElement);
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.top = '0px';

      window.requestAnimationFrame(update);

      function update() {
        stats.begin();
        requestAnimationFrame(update);
        stats.end();
      }
    </script>
  </body>
</html>
Heinzlmaen
  • 869
  • 10
  • 20