HTML5 Canvas Batch Draw Tip

Update: this demo is not relevant with the new konva@8. In the new version, Konva is doing all batching draws automatically on any changes on canvas.

The demo may be still relevant if you use Konva.autoDrawEnabled = false.

In some situations, we may want to update a Konva shape as fast as possible,
but without causing too many redraws. For example, if we want to update an
element on the stage via mousemove, we don’t want to redraw the layer with the
draw() method, because the mousemove event could be fired hundreds of times per
second, which would result in a forced frame rate of over a hundred frames per second.
Often times this can cause jumpy animations because browsers simply can’t handle excessive redraws.

For situations like this, it’s much better to use the batchDraw() method
which automatically hooks redraws into the Konva animation engine.
No matter how many times you call batchDraw(), Konva will automatically
limit the number of redraws per second based on the maximum number of frames
per second that the browser can handle at any given point in time.

Instructions: Move your mouse over the stage to spin the rectangle

Konva Batch Draw Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Batch Draw Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
// disable auto draw for the demo
// most applications don't need that
Konva.autoDrawEnabled = false;

var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

var layer = new Konva.Layer();

var rect = new Konva.Rect({
x: 110,
y: 100,
width: 200,
height: 20,
offset: {
x: 100,
y: 10,
},
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});

// add the shape to the layer
layer.add(rect);

// add the layer to the stage
stage.add(layer);

stage.on('mousemove', function () {
rect.rotate(5);
layer.batchDraw();
});
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.