I'm looking to find a way to programmatically animate stage scrolling. Here's an example that I've put together (looking at the examples and docs that Konvajs has): https://jsbin.com/tetakaf/edit?html,output
As you can see, the stage is draggable and the hexagon movement is animated so that it goes out of the viewport to the right. You can find it by dragging the stage to the left once the animation stops.
What I'm looking for is for the stage/viewport to also scroll along with the hexagon so that when the hexagon stops, the stage is centered on the viewport.
Is there a way to achieve this?
Here's the code from the jsbin:
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Animate Position Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
draggable: true,
});
var layer = new Konva.Layer();
var hexagon = new Konva.RegularPolygon({
x: stage.width() / 2,
y: stage.height() / 2,
sides: 6,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
layer.add(hexagon);
stage.add(layer);
layer.draw();
var velocity = 500;
var anim = new Konva.Animation(function(frame){
var dist = velocity * (frame.timeDiff / 1000);
if (stage.x() > stage.width() * 0.75) {
anim.stop();
}
stage.move({x: dist, y: 0});
}, layer);
anim.start();
</script>
</body>
</html>
Thanks, K
You can use stage.to()
method to make a simple tween at the end of the main animation:
var velocity = 500;
var anim = new Konva.Animation(function(frame){
var dist = velocity * (frame.timeDiff / 1000);
if (stage.x() > stage.width() * 0.75) {
anim.stop();
stage.to({ x: 0});
}
stage.move({x: dist, y: 0});
//stage.draw();
}, layer);