响应式画布舞台演示

你需要响应式/自适应画布来满足你的桌面和移动应用吗?

首先,有许多方法可以使你的画布舞台“响应式”。
而且你可能需要为不同的应用程序设置不同的行为。

本演示将向你展示最简单的解决方案。我们将通过缩放将画布舞台适应用户窗口。
在演示中,我们只关注舞台的宽度。如果你需要高度也适应,你可能需要添加额外的逻辑。

使用以下链接在新窗口打开演示:

打开演示!

并尝试调整浏览器窗口的大小。

响应式画布舞台演示view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Responsive Canvas 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 scene virtual size will be 1000x1000px
// but the real size will be different to fit user's page
var sceneWidth = 1000;
var sceneHeight = 1000;

var stage = new Konva.Stage({
container: 'container',
// first just set set as is
width: sceneWidth,
height: sceneHeight,
});

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 container
var containerWidth = container.offsetWidth;

// but we also make the full scene visible
// so we need to scale all objects on canvas
var scale = containerWidth / sceneWidth;

stage.width(sceneWidth * scale);
stage.height(sceneHeight * scale);
stage.scale({ x: scale, y: scale });
}

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