Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>sqrt to mouse</title>
- </head>
- <body>
- <canvas id="canvas" width="700" height="700"></canvas>
- <script>
- var WIDTH = 700;
- var HEIGHT = 700;
- var rectSide = 25;
- var canvas = document.getElementById("canvas");
- canvas.onmousemove = onMouseMove;
- canvas.width = WIDTH;
- canvas.height = HEIGHT;
- var context = canvas.getContext("2d");
- var sq = new Sqrt(10, 10, rectSide, rectSide, context);
- var mouseX = 0;
- var mouseY = 0;
- var speed = 2;
- requestAnimationFrame(render);
- function render()
- {
- context.clearRect(0, 0, WIDTH, HEIGHT);
- context.strokeRect(0, 0, WIDTH, HEIGHT);
- sq.updatePosition(mouseX, mouseY);
- sq.fillSqrt();
- requestAnimationFrame(render);
- }
- function onMouseMove(event)
- {
- mouseX = event.pageX;
- mouseY = event.pageY;
- }
- function Sqrt(x, y, w, h, context)
- {
- this.x = x;
- this.y = y;
- this.width = w;
- this.height = h;
- this.context = context;
- this.fillSqrt = function ()
- {
- return this.context.fillRect(this.x, this.y, this.width, this.height);
- };
- this.updatePosition = function (x, y)
- {
- var startX = this.x,
- startY = this.y,
- finishX = x - this.width - 5,
- finishY = y - this.height - 5;
- // проверка на то, достиг ли квадрат курсор:
- if (!(startX + speed > finishX && startX < finishX + speed && startY + speed > finishY && startY < finishY + speed))
- {
- this.x += speed * (finishX - startX > 0 ? 1 : -1);
- this.y += speed * (finishY - startY > 0 ? 1 : -1);
- // корректировка, чтобы не "уехал" влево-вверх:
- if (this.x < 0)
- this.x = 0;
- if (this.y < 0)
- this.y = 0;
- this.context.fillStyle = "green";
- }
- else
- {
- //достигли курсор
- this.context.fillStyle = "red";
- }
- }
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement