Zooming stage relative to pointer position

获取Konva最新的信息

Instructions: Mousewheel over canvas.

Konva Zoom Image on Hover Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Zoom Relative to Stage 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
});

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

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

layer.draw();

var scaleBy = 1.01;
stage.on('wheel', e => {
e.evt.preventDefault();
var oldScale = stage.scaleX();

var mousePointTo = {
x: stage.getPointerPosition().x / oldScale - stage.x() / oldScale,
y: stage.getPointerPosition().y / oldScale - stage.y() / oldScale
};

var newScale =
e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;
stage.scale({ x: newScale, y: newScale });

var newPos = {
x:
-(mousePointTo.x - stage.getPointerPosition().x / newScale) *
newScale,
y:
-(mousePointTo.y - stage.getPointerPosition().y / newScale) *
newScale
};
stage.position(newPos);
stage.batchDraw();
});
</script>
</body>
</html>
Next