перемещение фигуры на холсте с помощью EventListener - PullRequest
0 голосов
/ 01 октября 2018

Я сделал код, но единственное, что я не могу сделать, это то, что я хочу, чтобы круг двигался только тогда, когда мышь входит в круг, тогда он следует за мышью, как показано ниже.Круг начинает двигаться, когда я вхожу в окно, я хочу, чтобы он начинал двигаться, когда я вхожу в круг. Я не могу применить синтаксис здесь, любая помощь будет признательна

<!--
For this assignment, create an event listener that is triggered when the mouse 
moves through the #cont div. Using pageVars and offsets, dynamically set the
top and left style properties of the #circ1 div so that the circle follows the 
user's mouse.
-->


<html>

<head>
  <title>basic_canvas</title>

  <style>
    div {
      position: absolute;
    }
    
    #cont {
      margin: 0 auto;
      left: 0;
      right: 0;
      width: 800px;
      height: 600px;
    }
    
    .col {
      width: 365px;
      height: 380px;
      padding: 10px;
      background-color: rgba(110, 25, 75, 0.2);
    }
    
    #c2 {
      left: 405px;
    }
    
    .lower {
      width: 100%;
      height: 200px;
      top: 400px;
    }
    
    .circ {
      width: 100px;
      height: 100px;
      border-radius: 50px;
      background: -webkit-linear-gradient(top, #3498db, #2980b9);
      background: -moz-linear-gradient(top, #3498db, #2980b9);
      background: -ms-linear-gradient(top, #3498db, #2980b9);
      background: -o-linear-gradient(top, #3498db, #2980b9);
      background: linear-gradient(to bottom, #3498db, #2980b9);
      box-shadow: 0px 0px 5px black;
    }
    
    .circ:hover {
      background: -webkit-linear-gradient(top, #3cb0fd, #3498db);
      background: -moz-linear-gradient(top, #3cb0fd, #3498db);
      background: -ms-linear-gradient(top, #3cb0fd, #3498db);
      background: -o-linear-gradient(top, #3cb0fd, #3498db);
      background: linear-gradient(to bottom, #3cb0fd, #3498db);
      box-shadow: 0px 0px 10px black;
    }
    
    .text {
      width: 360px;
    }
    
    #circ1 {
      top: 20px;
      left: 350px;
    }
  </style>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

  <script>
    //global vars
    var mycanvas;
    var ctx;

    //make a ready handler for our page to trigger my javascript
    $(document).ready(function() {
      //event listener attached to the #cont element here
      $("#cont").mouseenter(function() {
        $(document).mousemove(function(e) {
          var x = e.pageX;
          var y = e.pageY;
          $("#circ1").css({
            "top": y,
            "left": x
          });
        });
      });

    });

    /*
     *  write a function called by the mousemove listener
     *  inside this function, calculate the x and y coordinates
     *  of the mouse and translate these to top and left css properties
     *  finally, set the top and left of the #circ1 element
     *  offsetX and offsetY are the same thing as mouseX and mouseY ->system variables
        
        
     *  this works for chrome
        var posX = e.offsetX;
        var posY = e.offsetY;
        
     *  this works for firefox
        var posX = e.pageX - canvas.offsetLeft;
        var posY = e.pageY - canvas.offsetTop;
     * 
    */




    function degToRad(deg) {
      radians = (deg * Math.PI / 180) - Math.PI / 2;
      return radians;
    }

    function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }

    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
  </script>

</head>

<body>

  <div id="cont">
    <div class="col" id="c1">
      <div class="text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quam turpis, maximus sit amet gravida ut, vestibulum nec lectus. Sed risus est, ultricies non quam in, tristique bibendum augue. Etiam accumsan est viverra lectus feugiat interdum. Duis
        dignissim nisi consectetur suscipit consectetur. Phasellus nulla augue, tincidunt ac pellentesque faucibus, iaculis a arcu. Mauris pretium, augue ut malesuada cursus, lorem mauris sodales sapien, vel mollis libero libero vel nisi. Nam viverra
        arcu at nibh vehicula, non sagittis arcu tincidunt.
      </div>
    </div>

    <div class="col" id="c2">
      <div class="text">
        Aenean sagittis et nulla quis interdum. Nam est tellus, lobortis eget faucibus a, porta vel dolor. Nulla quam magna, volutpat ut malesuada quis, cursus et neque. Nulla facilisis rutrum eros, congue porta orci maximus vitae. Phasellus a sollicitudin sem.
        Maecenas vestibulum odio nec justo efficitur, quis consequat orci tempus. Aliquam erat volutpat. Fusce mollis facilisis justo vitae auctor. Maecenas porttitor luctus urna, ultricies volutpat purus elementum sed. Mauris maximus sodales ante, ut
        lobortis libero faucibus quis. Cras turpis leo, vehicula sed mattis ac, dignissim egestas sem. Ut elementum a tellus vel faucibus.
      </div>
    </div>

    <div class="lower" id="l1">

      <div class="circ" id="circ1"></div>

    </div>

  </div>

</body>

</html>

1 Ответ

0 голосов
/ 01 октября 2018

Понятия не имею, почему это не работает для меня на SO.Когда я добавляю jquery, я получаю консоль, полную ошибок.Это ссылка на codepen demo

Изменения, которые я сделал:

  1. В JavaScript я использую var e.clientX-50 и e.clientY-50;вместо pageX и pageY.-50, потому что я хочу, чтобы мышь находилась в центре круга.В противном случае я получу указатель в верхнем левом углу: .circ

  2. В CSS

Я добавил .circ {position: absolute;} в противном случае верхнее и левое свойства не имеют смысла.Пожалуйста, проверьте код, чтобы увидеть строки кода, которые я удалил.

 //global vars
    var mycanvas;
    var ctx;

    //make a ready handler for our page to trigger my javascript
    $(document).ready(function() {
      //event listener attached to the #cont element here
      //$("#cont").mouseenter(function() {
        $(document).mousemove(function(e) {
          console.log(e)
          var x = e.clientX-50;
          var y = e.clientY-50;
          $("#circ1").css({
            "top": y,
            "left": x
          });
        });
      });

    //});

    /*
     *  write a function called by the mousemove listener
     *  inside this function, calculate the x and y coordinates
     *  of the mouse and translate these to top and left css properties
     *  finally, set the top and left of the #circ1 element
     *  offsetX and offsetY are the same thing as mouseX and mouseY ->system variables
     *  this works for chrome
        var posX = e.offsetX;
        var posY = e.offsetY;

     *  this works for firefox
        var posX = e.pageX - canvas.offsetLeft;
        var posY = e.pageY - canvas.offsetTop;
     * 
    */




    function degToRad(deg) {
      radians = (deg * Math.PI / 180) - Math.PI / 2;
      return radians;
    }

    function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }

    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
  div {
      position: absolute;
    }

    #cont {
      margin: 0 auto;
      left: 0;
      right: 0;
      width: 800px;
      height: 600px;
    }

    .col {
      width: 365px;
      height: 380px;
      padding: 10px;
      background-color: rgba(110, 25, 75, 0.2);
    }

    #c2 {
      left: 405px;
    }

    .lower {
      width: 100%;
      height: 200px;
      /*top: 400px;*/
    }

    .circ {
      width: 100px;
      height: 100px;
      border-radius: 50px;
      background: -webkit-linear-gradient(top, #3498db, #2980b9);
      background: -moz-linear-gradient(top, #3498db, #2980b9);
      background: -ms-linear-gradient(top, #3498db, #2980b9);
      background: -o-linear-gradient(top, #3498db, #2980b9);
      background: linear-gradient(to bottom, #3498db, #2980b9);
      box-shadow: 0px 0px 5px black;
      position:absolute;
    }

    .circ:hover {
      background: -webkit-linear-gradient(top, #3cb0fd, #3498db);
      background: -moz-linear-gradient(top, #3cb0fd, #3498db);
      background: -ms-linear-gradient(top, #3cb0fd, #3498db);
      background: -o-linear-gradient(top, #3cb0fd, #3498db);
      background: linear-gradient(to bottom, #3cb0fd, #3498db);
      box-shadow: 0px 0px 10px black;
    }

    .text {
      width: 360px;
    }
    /*
    #circ1 {
      top: 20px;
      left: 350px;
    }*/
<div id="cont">
    <div class="col" id="c1">
      <div class="text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quam turpis, maximus sit amet gravida ut, vestibulum nec lectus. Sed risus est, ultricies non quam in, tristique bibendum augue. Etiam accumsan est viverra lectus feugiat interdum. Duis
        dignissim nisi consectetur suscipit consectetur. Phasellus nulla augue, tincidunt ac pellentesque faucibus, iaculis a arcu. Mauris pretium, augue ut malesuada cursus, lorem mauris sodales sapien, vel mollis libero libero vel nisi. Nam viverra
        arcu at nibh vehicula, non sagittis arcu tincidunt.
      </div>
    </div>

    <div class="col" id="c2">
      <div class="text">
        Aenean sagittis et nulla quis interdum. Nam est tellus, lobortis eget faucibus a, porta vel dolor. Nulla quam magna, volutpat ut malesuada quis, cursus et neque. Nulla facilisis rutrum eros, congue porta orci maximus vitae. Phasellus a sollicitudin sem.
        Maecenas vestibulum odio nec justo efficitur, quis consequat orci tempus. Aliquam erat volutpat. Fusce mollis facilisis justo vitae auctor. Maecenas porttitor luctus urna, ultricies volutpat purus elementum sed. Mauris maximus sodales ante, ut
        lobortis libero faucibus quis. Cras turpis leo, vehicula sed mattis ac, dignissim egestas sem. Ut elementum a tellus vel faucibus.
      </div>
    </div>

    <div class="lower" id="l1">

      <div class="circ" id="circ1"></div>

    </div>

  </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...