Rough.js jittering/shaking with requestAnimationFrame

Viewed 147

I have a simple canvas in which I'm drawing a rectangle using Rough.js library. The issue I'm having is Rough js randomizing the draw pattern so each time the rectangle method is called, it seems to shake/jitter inside requestAnimationFrame. I'm not too familiar with the library I'm wondering if anyone here has any experience to either set some constants to force the rectangle to be drawn the exact same way or disable randomisation altogether.

<html>
    <head>
        <script type='text/javascript' src="https://unpkg.com/roughjs@4.3.1/bundled/rough.js"></script>
    </head>
    <body>

        <canvas id="canvas" width="480" height="640"></canvas>

    </body>
    <script>
        window.addEventListener('DOMContentLoaded',event=>{
            let canvas = document.getElementById("canvas");
            let ctx = canvas.getContext('2d');
            let r = rough.canvas(canvas);
            function draw(tick){
                requestAnimationFrame(draw);
                ctx.clearRect(0,0,480,640);
                r.rectangle(50, 50, 80, 80, {
                    fill: 'rgba(255,0,200,0.2)',
                    fillStyle: 'solid' // solid fill
                });
            }
            requestAnimationFrame(draw);

        });
    </script>
</html>

When you run the snippet you can see the jittering/shaking. That's what I wish to disable.

1 Answers

You'll want to use the RoughGenerator to create a rectangle instruction once and reuse it:

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d");
const r = rough.canvas(canvas);

// First we set up a rectangle
const rect = r.generator.rectangle(50, 50, 80, 80, {
  fill: 'rgba(255,0,200,0.2)',
  fillStyle: 'solid' // solid fill
});

(function draw(tick) {
  requestAnimationFrame(draw);
  ctx.clearRect(0, 0, 480, 640);

  // Then we draw it as many times as we want
  r.draw(rect);
})();
<script src="https://unpkg.com/roughjs@4.3.1/bundled/rough.js"></script>
<canvas></canvas>

Related