LoginSignup
3
6

More than 3 years have passed since last update.

【コピペで動く】ドラッグアンドドロップで画像を移動し、クリックで画像を回転させる【jQuery】

Last updated at Posted at 2019-06-14

はじめに

マウス操作(ドラッグアンドドロップ、クリック)でDOM(HTMLの要素)を移動、回転させるためのコード
サンプルコードではimgタグを使っているが、divタグでもpタグでも動きます。
動かしたい要素のstyleがposition: absolute;ではないと動きません。

デモ

a6d1706884f1e5cd706f72fc0443db52.gif

サンプルコード

index.html
<!DOCTYPE html>
<html lang="ja" dir="ltr">

<head>
    <meta charset="utf-8">
    <title>DOMを回転</title>
</head>
<body>
    <style media="screen">
        .rotation {
            transform: rotate(0deg);
            position: absolute;
            top: 100px;
            left: 250px;
        }
    </style>
    <img class="rotation" src="https://2.bp.blogspot.com/-54PaAjuNmgE/WwUdT-7717I/AAAAAAABMVc/zzgxyc9F7A8ZfAruS9tWcEUg8QJ3RcFEACLcBGAs/s800/vr_motion_tracking_6dof.png" id="illust" alt="">

  <!-- jqueryとドラッグアンドドロップで移動できるライブラリをインポート -->
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

    <script>
        //ドラッグアンドドロップで移動させたい要素をセレクタで指定
        $("#illust").draggable();

        //id回転させたい要素セレクタで指定
        //今回は id="illust" が入っている画像を回転させたいので #illust
    //クリックされるたびに呼び出される
        $('#illust').click(function() {
            console.log('クリックされました!');
            let now_angle = getRotationDegrees($(this));
      //10度ずつ回転させる
            let next_angle = now_angle + 10
            $(this).css('transform', 'rotate(' + next_angle + 'deg)');
        });

        //参考にしたサイト https://codeday.me/jp/qa/20181219/78103.html
        //要素を指定して、transformのrotateを求める
        function getRotationDegrees(obj) {
            var matrix = obj.css("-webkit-transform") ||
                obj.css("-moz-transform") ||
                obj.css("-ms-transform") ||
                obj.css("-o-transform") ||
                obj.css("transform");
            if (matrix !== 'none') {
                var values = matrix.split('(')[1].split(')')[0].split(',');
                var a = values[0];
                var b = values[1];
                var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
            } else {
                var angle = 0;
            }
            return (angle < 0) ? angle + 360 : angle;
        }
    </script>
</body>

</html>

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6