Reputation: 31
my problem is following: I have couple of shapes on stage and on button click I need to zoom to specific shape and its position. Do you have any ideas how to do it?
I have already checked tutorials for zooming to pointer position and to center of the stage.
Upvotes: 2
Views: 1776
Reputation: 20288
There are many possible solutions for that case. Also, it may depend on what exactly do you want to "zoom". Stage, Layer, Group? So depends on the structure of your scene tree.
As a possible solution we can do this:
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
for (var i = 0; i < 10; i ++) {
const shape = new Konva.Circle({
x: stage.width() * Math.random(),
y: stage.height() * Math.random(),
radius: 30 + Math.random() * 30,
fill: Konva.Util.getRandomColor()
});
layer.add(shape);
}
stage.on('click tap', (e) => {
// if we have scale, just reset
const zoomed = stage.scaleX() !== 1;
if (zoomed) {
stage.to({
x: 0,
y: 0,
scaleX: 1,
scaleY: 1
});
return;
}
// ignore if clicked not on shape
const clickOnShape = e.target instanceof Konva.Shape;
if (!clickOnShape) {
return;
}
// where shape is placed
const box = e.target.getClientRect();
// how much do we need to zoom for that
const scale = Math.min(stage.width() / box.width, stage.height() / box.height);
// let's do it
stage.to({
x: -box.x * scale,
y: -box.y * scale,
scaleX: scale,
scaleY: scale,
})
})
<script src="https://unpkg.com/konva@^8/konva.min.js"></script>
<div id="container"></div>
Upvotes: 1
Reputation: 9525
Working with canvas, as it is a 2D display, you are most usually dealing with problems related to rectangles.
In this case we can break the problem into 2 parts:
Compute the bounding rectangle of the selected shape then compute the x & y amounts to adjust the stage position (another rectangle) to have the shape rectangle appear centered in the canvas. A couple of hints to help you - for shape rect look at getClientRect(). For canvas rect you need the rect for the viewport (the html canvas element) and not the stage since the stage can be 'bigger' then the canvas element in which it is being viewed.
Compute the amount of scaling to apply to achieve the desired level of zooming to get the shape rect to fit pleasingly into the canvas element. Hint - you will probably want to apply an adjustment factor to have the shape keep some space around it so as it looks pleasing.
Upvotes: 0