gpt4 book ai didi

javascript - KonvaJS - 始终在 Canvas 中心缩放

转载 作者:行者123 更新时间:2023-12-04 12:37:31 26 4
gpt4 key购买 nike

我正在努力修改下面的代码,以便在缩放滚动时,图像在图像的中心总是被缩放,而不取决于光标位置(所以图像不会移动,它只是放大/缩小并不重要,你的光标在哪里,整个 Canvas 总是在中心放大。

所以问题是 - 如何始终在中心缩放图像?谢谢!

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 pointer = stage.getPointerPosition();

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

var newScale =
e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;

stage.scale({
x: newScale,
y: newScale
});

var newPos = {
x: pointer.x - mousePointTo.x * newScale,
y: pointer.y - mousePointTo.y * newScale,
};

stage.position(newPos);
stage.batchDraw();
});
<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
<div id="container"></div>

最佳答案

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 center = {
x: stage.width() / 2,
y: stage.height() / 2,
};

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

var newScale =
e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;

stage.scale({
x: newScale,
y: newScale
});

var newPos = {
x: center.x - relatedTo.x * newScale,
y: center.y - relatedTo.y * newScale,
};

stage.position(newPos);
stage.batchDraw();
});
<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
<div id="container"></div>

关于javascript - KonvaJS - 始终在 Canvas 中心缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62941852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com