Responsive Canvas Stage Demo

Do you need responsive/adaptive canvas for you desktop and mobile applications?

So first of all, there are many way to make your canvas stage “responsive”.
And you may need a different behavior for different applications.

This demo will show you the simplest solution. We will fit a canvas stage into user window with scaling.
In the demo we will care only about stage WIDTH. You may need to add extra logic if you need to fit height too.

Instructions: open demo on new window with this link:

Open Demo!

And try to resize a browser window.

Responsive Canvas Stage Demoview raw
<!DOCTYPE html>
<html>

<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Zoom Image on Hover Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}

#stage-parent {
width: 100%;
}
</style>
</head>

<body>
<div id="stage-parent">
<div id="container"></div>
</div>
<script>
// let's think our stage virtual size will be 1000x1000px
// but the real size will be different to fit user's page
// so the stage will be 100% visible on any device
var stageWidth = 1000;
var stageHeight = 1000;

var stage = new Konva.Stage({
container: 'container',
width: stageWidth,
height: stageHeight
});

var layer = new Konva.Layer();
stage.add(layer);

// add circle into center
var circle = new Konva.Circle({
radius: 50,
fill: 'red',
x: stage.width() / 2,
y: stage.height() / 2
});
layer.add(circle);

// rectangle in bottom right of the stage
var rect = new Konva.Rect({
fill: 'green',
x: stage.width() - 100,
y: stage.height() - 100,
width: 100,
height: 100
});
layer.add(rect);


function fitStageIntoParentContainer() {
var container = document.querySelector('#stage-parent');

// now we need to fit stage into parent
var containerWidth = container.offsetWidth;
// to do this we need to scale the stage
var scale = containerWidth / stageWidth;


stage.width(stageWidth * scale);
stage.height(stageHeight * scale);
stage.scale({ x: scale, y: scale });
stage.draw();
}

fitStageIntoParentContainer();
// adapt the stage on any window resize
window.addEventListener('resize', fitStageIntoParentContainer);
</script>

</body>

</html>