This commit is contained in:
Ilya Kantor 2020-03-24 05:47:48 +03:00
parent 6700835b1f
commit fd81db7096
4 changed files with 12 additions and 7 deletions

View file

@ -9,7 +9,7 @@
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
@ -20,7 +20,7 @@
<div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
<img src="https://js.cx/clipart/ball.svg" height="40" width="40" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>
@ -38,4 +38,4 @@
</body>
</html>
</html>

View file

@ -24,17 +24,22 @@ ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px';
```
**Attention: the pitfall!**
Now the ball is finally centered.
````warn header="Attention: the pitfall!"
The code won't work reliably while `<img>` has no width/height:
```html
<img src="ball.png" id="ball">
```
````
When the browser does not know the width/height of an image (from tag attributes or CSS), then it assumes them to equal `0` until the image finishes loading.
After the first load browser usually caches the image, and on next loads it will have the size immediately. But on the first load the value of `ball.offsetWidth` is `0`. That leads to wrong coordinates.
So the value of `ball.offsetWidth` will be `0` until the image loads. That leads to wrong coordinates in the code above.
After the first load, the browser usually caches the image, and on reloads it will have the size immediately. But on the first load the value of `ball.offsetWidth` is `0`.
We should fix that by adding `width/height` to `<img>`:

View file

@ -26,7 +26,7 @@
<script>
// ball.offsetWidth=0 before image loaded!
// ball.offsetWidth=0 before image loaded!
// to fix: set width
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px'
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px'

View file

@ -10,7 +10,7 @@ Here's how the source document looks:
What are coordinates of the field center?
Calculate them and use to place the ball into the center of the field:
Calculate them and use to place the ball into the center of the green field:
[iframe src="solution" height=180]