JSFiddle - React, Tailwind, and code Playground
by zlojnaxa
HTML
<div class="workSpace">
<div class="box" id="one" data-speed-x="2" data-speed-y="6">
<img src="https://data.pixiz.com/output/user/frame/preview/400x400/5/5/8/3/713855_be03a.jpg">
</div>
<div class="box" id="two" data-speed-x="7" data-speed-y="2">
<img src="http://e-opinions.ru/image.aspx?f=uploads/wtiquhwubuqlvnx.jpg&max=380">
</div>
</div>
CSS
html, body{
margin: 0px 0px 0px 0px;
width: 100%;
height: 100%;
overflow: hidden;
}
.workSpace{
width: 100%;
height: 100%;
background: #eee5ff;
overflow: hidden;
}
img{
width: 100%;
position: relative;
top: -10px;
}
#one{
width: 440px;
height: 283px;
overflow: hidden;
position: absolute;
left: 10px;
top: 0px;
}
#two{
width: 430px;
height: 265px;
overflow: hidden;
position: absolute;
left: 640px;
top: 40px;
}
.coord{
width: 100%;
height: 120px;
background: rgba(255, 235, 59, 0.7);
position: relative;
top: -290px;
text-align: left;
color: #ff1100;
font-size: 40px;
font-family: comic sans ms;
line-height: 56px;
display: none;
}
JavaScript
funnyBoxes();
function funnyBoxes(){ var box = document.querySelectorAll('.box'), workSpace = document.querySelectorAll('.workSpace')[0], interval;
var workArea = {}, sizeBox = {}, coord = {}, move = {}, speed = {};
var coordinates = document.querySelectorAll('.coord'); // удалить после отладки
[...box].map((e,i)=>{
workArea[i] ={ x : workSpace.offsetWidth - e.offsetWidth, y : workSpace.offsetHeight - e.offsetHeight };
sizeBox[i] ={ x : e.offsetWidth, y : e.offsetHeight };
coord[i] ={ x : +window.getComputedStyle(e, null).getPropertyValue('left').replace('px',''), y : +window.getComputedStyle(e, null).getPropertyValue('top').replace('px','') };
speed[i] ={ x : +e.getAttribute('data-speed-x'), y : +e.getAttribute('data-speed-y') };
move[i] = { right : true, down : true };
});
calculateMoves();
function calculateMoves(){
interval = requestAnimationFrame(calculateMoves);
[...box].map((e,i)=>{
coord[i].x <= workArea[i].x && move[i].right || coord[i].x <= 0 ? moveRight(e,i) : '';
coord[i].x >= workArea[i].x || coord[i].x < workArea[i].x && !move[i].right ? moveLeft(e,i) : '';
coord[i].y <= workArea[i].y && move[i].down || coord[i].y <= 0 ? moveDown(e,i) : '';
coord[i].y >= workArea[i].y || coord[i].y < workArea[i].y && !move[i].down ? moveUp(e,i) : '';
});
coordinates[0].innerHTML = 'x: ' + coord[0].x + ' <br> y: ' + coord[0].y; // удалить после отладки
coordinates[1].innerHTML = 'x: ' + coord[1].x + ' <br> y: ' + coord[1].y; // удалить после отладки
}
function moveRight(e,i){
move[i].right = true;
coord[i].x += speed[i].x;
e.style.left = coord[i].x + 'px';
}
function moveLeft(e,i){
move[i].right = false;
coord[i].x -= speed[i].x;
e.style.left = coord[i].x + 'px';
}
function moveDown(e,i){
move[i].down = true;
coord[i].y += speed[i].y;
e.style.top = coord[i].y + 'px';
}
function...