-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveBallAcrossField.html
85 lines (68 loc) · 2.89 KB
/
moveBallAcrossField.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#field {
width: 200px;
height: 150px;
border: 10px solid black;
background-color: #00FF00;
/* position: relative; */
overflow: hidden;
cursor: pointer;
}
#ball {
position: absolute;
width: 40px;
height: 40px;
transition: all 1s;
}
</style>
</head>
<body style="height:2000px;">
Click on a field to move the ball there.
<br> The ball should never leave the field.
<div id="field">
<img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
</div>
<script>
let fieldRect = field.getBoundingClientRect();
let innerFieldLT = {
x: fieldRect.left + (field.offsetWidth - field.clientWidth) / 2,
y: fieldRect.top + (field.offsetHeight - field.clientHeight) / 2
}
let innerFieldRB = {
x: fieldRect.right - (field.offsetWidth - field.clientWidth) / 2,
y: fieldRect.bottom - (field.offsetHeight - field.clientHeight) / 2
}
field.onclick = function (event) {
console.log(`x:${event.clientX}, y:${event.clientY}`);
let fieldRect = field.getBoundingClientRect();
let innerFieldLT = {
x: fieldRect.left + (field.offsetWidth - field.clientWidth) / 2,
y: fieldRect.top + (field.offsetHeight - field.clientHeight) / 2
}
let innerFieldRB = {
x: fieldRect.right - (field.offsetWidth - field.clientWidth) / 2,
y: fieldRect.bottom - (field.offsetHeight - field.clientHeight) / 2
}
let ballRect = ball.getBoundingClientRect();
let halfBallWidth = ballRect.width / 2, halfBallHeight = ballRect.height / 2;
let fieldWidth = field.clientWidth, fieldHeight = field.clientHeight;
let leftValue = event.clientX - halfBallWidth;
leftValue = Math.max(innerFieldLT.x, leftValue);
leftValue = Math.min(innerFieldRB.x - halfBallWidth * 2, leftValue);
let topValue = event.clientY - halfBallHeight;
topValue = Math.max(innerFieldLT.y, topValue);
topValue = Math.min(innerFieldRB.y - halfBallHeight * 2, topValue);
ball.style.left = leftValue + window.pageXOffset + 'px';
ball.style.top = topValue + window.pageYOffset + 'px';
}
</script>
</body>
</html>