gpt4 book ai didi

javascript - 鼠标滚轮缩放

转载 作者:太空狗 更新时间:2023-10-29 16:40:17 24 4
gpt4 key购买 nike

所以我在 Canvas 上工作,你只能将图像从一侧拖到另一侧,然后使用鼠标滚轮通过放大和缩小来调整图像大小这里是我到目前为止的代码请随意询问更多细节。我正在尝试找到一种紧凑的方式来执行此操作并且需要最少的代码。

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<script src="kinetic-v5.1.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="container"></div>

<script type="text/javascript">
function drawImage(imageObj) {
var stage = new Kinetic.Stage({
container: "container",
width: 1800,
height: 800
});
var layer = new Kinetic.Layer();

// image
var image1 = new Kinetic.Image({
image: imageObj,
x: stage.getWidth() / 2 - 896 / 1,
y: stage.getHeight() / 2 - 255 / 2,
width: 200,
height: 157,
draggable: true,
dragBoundFunc: function (pos) {
if (pos.x < this.minX) { }
this.minX = pos.x;
return {
x: pos.x,
y: this.getAbsolutePosition().y
}
}
});


// add cursor styling
image1.on('mouseover', function() {
document.body.style.cursor = 'pointer';
});
image1.on('mouseout', function() {
document.body.style.cursor = 'default';
});

layer.add(image1);
stage.add(layer);
}
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = 'image1.png';

</script>
</body>
</html>

最佳答案

一种方法是使用缩放助手。例如:

var zoomHelper = {
stage: null,
scale: 1,
zoomFactor: 1.1,
origin: {
x: 0,
y: 0
},
zoom: function(event) {
event.preventDefault();
var delta;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
if (event.originalEvent.detail > 0) {
//scroll down
delta = 0.2;
} else {
//scroll up
delta = 0;
}
} else {
if (event.originalEvent.wheelDelta < 0) {
//scroll down
delta = 0.2;
} else {
//scroll up
delta = 0;
}
}
var evt = event.originalEvent,
mx = evt.clientX - zoomHelper.stage.getX(),
my = evt.clientY - zoomHelper.stage.getY(),
zoom = (zoomHelper.zoomFactor - delta),
newscale = zoomHelper.scale * zoom;
zoomHelper.origin.x = mx / zoomHelper.scale + zoomHelper.origin
.x - mx / newscale;
zoomHelper.origin.y = my / zoomHelper.scale + zoomHelper.origin
.y - my / newscale;
zoomHelper.stage.setOffset({
x: zoomHelper.origin.x,
y: zoomHelper.origin.y
});
zoomHelper.stage.setScale({
x: newscale,
y: newscale
});
zoomHelper.stage.draw();
zoomHelper.scale *= zoom;
}
};

这是一个demo您作为示例提供的代码略有变化。

关于javascript - 鼠标滚轮缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174511/

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