Pat*_*kkx 4 javascript css canvas konvajs
我正在努力修改下面的代码,因此当缩放滚动时,图像始终在图像的中心缩放,而不取决于光标位置(因此图像不会移动,它只是放大/缩小,无论光标在哪里)也就是说,整个画布始终在中心缩放)。
所以问题是 - 如何始终在中心缩放图像?谢谢你!
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();
});Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
<div id="container"></div>Run Code Online (Sandbox Code Playgroud)
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();
});Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
<div id="container"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4445 次 |
| 最近记录: |