如何使用kineticjs使用鼠标滚动旋转矩形? 下面的链接显示了在mousedown上使用jquery旋转形状。但我想使用mousewheel事件而不是mousePos,因为我的矩形是可拖动的。 http://www.lonhosford.com/content/html5/canvas/rotate_to_mouse.html
答案 0 :(得分:1)
KineticJS本身并不跟踪鼠标滚轮事件。
您可以使用jQuery +鼠标滚轮插件接收鼠标滚轮事件。
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.3/jquery.mousewheel.min.js"></script>
为什么选择jQuery?
您可以在没有jQuery +插件的情况下跟踪鼠标滚轮事件,但鼠标滚轮事件尚未在浏览器中标准化,因此跨浏览器的非jQuery解决方案会很复杂。
以下是如何在舞台容器上侦听鼠标滚轮事件并旋转Rect:
// set this variable to refer to the KineticJS rect you want to rotate
var theRectToRotate
// set this variable to the number of degrees to rotate when the user mousewheels
var degreeRotationPerMousewheelDelta=5;
// Use jQuery to listen for mousewheel events
// Then rotate the specified rect by the specified degree
$("#container").mousewheel(function(event, delta, deltaX, deltaY){
theRectToRotate.rotateDeg(delta* degreeRotationPerMousewheelDelta );
layer.draw();
event.preventDefault();
});
这是代码和小提琴:http://jsfiddle.net/m1erickson/kXJ5q/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
<script src="="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.3/jquery.mousewheel.min.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:300px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);
$("#container").mousewheel(function(event, delta, deltaX, deltaY){
console.log(delta+": "+deltaX+"/"+deltaY);
rect.rotateDeg(delta*5);
layer.draw();
event.preventDefault();
});
var rect = new Kinetic.Rect({
x: 100,
y: 100,
width: 100,
height: 70,
offset:[50,35],
fill: 'skyblue',
stroke: 'lightgray',
strokeWidth: 3
});
layer.add(rect);
layer.draw();
}); // end $(function(){});
</script>
</head>
<body>
<h3>Use mousewheel to rotate the rect</h3>
<h5>This requires a plugin:</h5>
<h5>https://github.com/brandonaaron/jquery-mousewheel </h5>
<div id="container"></div>
</body>
</html>
答案 1 :(得分:0)
假设您有办法知道当前聚焦/选择了哪个矩形(或者您希望它们全部同时旋转)。最简单的方法是不让它连续,即为每个鼠标轮事件旋转一定量。
要做到这一点,你需要获取事件的wheelDelta,检查它是正还是负,并按照设置的角度旋转你的矩形rect.setRotation(mySetAngleInRadians * isNegativeAngle)
,然后重绘图层。
如果你想连续滚动,那么你需要handle the cases where it isn't supported并决定一个与360度(完整圆圈)相对应的滚动距离值,然后执行以下操作:
rect.setRotation(ev.wheelDelta/fullScrollDistance * 2 * Math.PI)