Advertisement
vgarbuzov

sqrt to mouse

May 5th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>sqrt to mouse</title>
  6. </head>
  7. <body>
  8.     <canvas id="canvas"  width="700" height="700"></canvas>
  9. <script>
  10.  
  11.     var WIDTH = 700;
  12.     var HEIGHT = 700;
  13.     var rectSide = 25;
  14.  
  15.     var canvas = document.getElementById("canvas");
  16.     canvas.onmousemove = onMouseMove;
  17.     canvas.width = WIDTH;
  18.     canvas.height = HEIGHT;
  19.     var context = canvas.getContext("2d");
  20.  
  21.     var sq = new Sqrt(10, 10, rectSide, rectSide, context);
  22.  
  23.     var mouseX = 0;
  24.     var mouseY = 0;
  25.     var speed = 2;
  26.  
  27.     requestAnimationFrame(render);
  28.  
  29.  
  30.     function render()
  31.     {
  32.         context.clearRect(0, 0, WIDTH, HEIGHT);
  33.         context.strokeRect(0, 0, WIDTH, HEIGHT);
  34.         sq.updatePosition(mouseX, mouseY);
  35.         sq.fillSqrt();
  36.  
  37.         requestAnimationFrame(render);
  38.     }
  39.  
  40.     function onMouseMove(event)
  41.     {
  42.         mouseX = event.pageX;
  43.         mouseY = event.pageY;
  44.     }
  45.  
  46.     function Sqrt(x, y, w, h, context)
  47.     {
  48.         this.x = x;
  49.         this.y = y;
  50.         this.width = w;
  51.         this.height = h;
  52.         this.context = context;
  53.         this.fillSqrt = function ()
  54.         {
  55.             return this.context.fillRect(this.x, this.y, this.width, this.height);
  56.         };
  57.         this.updatePosition = function (x, y)
  58.         {
  59.             var startX = this.x,
  60.                     startY = this.y,
  61.                     finishX = x - this.width - 5,
  62.                     finishY = y - this.height - 5;
  63.  
  64.             // проверка на то, достиг ли квадрат курсор:
  65.             if (!(startX + speed > finishX && startX < finishX + speed && startY + speed > finishY && startY < finishY + speed))
  66.             {
  67.                 this.x += speed * (finishX - startX > 0 ? 1 : -1);
  68.                 this.y += speed * (finishY - startY > 0 ? 1 : -1);
  69.  
  70.                 // корректировка, чтобы не "уехал" влево-вверх:
  71.                 if (this.x < 0)
  72.                     this.x = 0;
  73.                 if (this.y < 0)
  74.                     this.y = 0;
  75.                 this.context.fillStyle = "green";
  76.             }
  77.             else
  78.             {
  79.                 //достигли курсор
  80.                 this.context.fillStyle = "red";
  81.             }
  82.         }
  83.     }
  84.  
  85.  
  86. </script>
  87.  
  88. </body>
  89. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement