0

kinectJS を使用して絶対回転ポイントを中心に画像を回転させたいと思います。たとえば、約

var rotatePoint = {x: 500, y: 500}

画像をクリックしてマウスを動かす、つまり画像をドラッグ アンド ドロップすることで、回転を初期化する必要があります。そうすることで、マウスが描いているのと同じ角度で回転するはずです。

昨日、私は一日中この問題に取り組んでいましたが、解決策が見つかりませんでした。

何か案は?

ありがとう!

4

2 に答える 2

0

三角法を使用して、固定された回転ポイントを中心に画像を移動できます

Math.atan2 を使用して、回転点に対するマウス位置の角度を計算します。

    var dx=mouseX-rotationPointX;
    var dy=mouseY-rotationPointY;
    var radianAngle=Math.atan2(dy,dx);

Math.cos と Math.sin を使用して、rotationPoint を中心に画像を移動します。

    var x=rotationPointX+radius*Math.cos(radianAngle)-imgWidth/2;
    var y=rotationPointY+radius*Math.sin(radianAngle)-imgHeight/2;
    image.setPosition(x,y);

これが実際のコード例です:

<!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.5.4.min.js"></script>

<style>
body{ padding:15px; }
#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);

    var rx=150;
    var ry=150;
    var radius=75;

    var image;;
    var imgWidth=50;
    var imgHeight=50;

    var rotationPoint=new Kinetic.Circle({
        x:rx,
        y:ry,
        radius:10,
        fill:"green"
    });
    layer.add(rotationPoint);


    $(stage.getContent()).on('mousemove', function (event) {

        // get the current mouse position on the stage
        var pos=stage.getMousePosition();
        var mouseX=parseInt(pos.x);
        var mouseY=parseInt(pos.y);

        // calculate the mouse angle relative 
        // to the rotation point [rx,ry]
        var dx=mouseX-rx;
        var dy=mouseY-ry;
        var radianAngle=Math.atan2(dy,dx);

        // "normalize" the angle so it always is in a proper range (0-2*PI)
        radianAngle=(radianAngle+Math.PI*2)%(Math.PI*2);

        // calculate the new image x,y 
        // based on the angle
        var x=rx+radius*Math.cos(radianAngle)-imgWidth/2;
        var y=ry+radius*Math.sin(radianAngle)-imgHeight/2;
        image.setPosition(x,y);

        layer.draw();
    });


    var img=new Image();
    img.onload=function(){
        image=new Kinetic.Image({
            image:img,
            x:0,
            y:0,
            width:imgWidth,
            height:imgHeight,
        });
        layer.add(image);
        layer.draw();
    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";


}); // end $(function(){});

</script>       
</head>

<body>
    <p>Move mouse to rotate image around</p>
    <p>the green dot which is located at</p>
    <p>the rotation point</p>
    <div id="container"></div>
</body>
</html>
于 2013-07-24T08:45:05.670 に答える