
공 튀기기를 만들어 보았습니다. 공은 div 엘레멘트로 position을 absolute로 주는 방식을 사용했습니다. 생각보다 고생해서 만들었는데, 코드가 마음에 들지는 않지만 그냥 올려봅니다.
버튼을 누르면 공이 움직이는 각도와 속도 그리고 공의 색깔이 변합니다.
<!DOCTYPE html>
<style>
#box {
border: 20px solid gray;
max-width: 800px;
height: 500px;
position: relative;
}
#ball {
width: 100px; height: 100px; border-radius: 50%;
position: absolute; top: 0; left: 0;
transform: translate(-50%, -50%);
background-color: hotpink;
transition: background-color 0.5s;
}
.myBtn {
padding: 8px 12px;
font-size: 16px;
}
</style>
<p>
<button class="myBtn" onclick="ballPlayObj.change()">Change</button>
</p>
<div id="box">
<div id="ball"></div>
</div>
<script>
var ballObj = {
radius: 0, px: 0, py: 0,
init: function(radius, px, py) {
this.radius = radius;
this.px = px;
this.py = py;
this.change();
},
change: function() {
var angle = Math.random() * Math.PI * 2;
var speed = Math.random() * 2.5 + 0.5; // 0.5 ~ 3
this.mx = Math.cos(angle) * speed;
this.my = Math.sin(angle) * speed;
},
move: function(box) {
for (var i = 0; i <= 20; i++) {
this.px += this.mx;
this.py += this.my;
if (this.px - this.radius < box.left && this.mx < 0) this.mx *= -1;
if (this.px + this.radius > box.right && this.mx > 0) this.mx *= -1;
if (this.py - this.radius < box.top && this.my < 0) this.my *= -1;
if (this.py + this.radius > box.bottom && this.my > 0) this.my *= -1;
}
}
};
var ballPlayObj = {
boxElem: document.getElementById("box"),
boxWidth: 0, boxHeight: 0,
ballElem: document.getElementById("ball"),
ballColors: ["hotpink", "orange", "yellow", "dodgerblue", "darkviolet",
"aqua", "sienna", "olive", "black", "red", "khaki", "silver"],
ballColor: 0,
getBoxSize: function() {
this.boxWidth = this.boxElem.clientWidth;
this.boxHeight = this.boxElem.clientHeight;
},
setBallPos: function() {
this.ballElem.style.left = ballObj.px + "px";
this.ballElem.style.top = ballObj.py + "px";
},
changeBallColor: function() {
while (true) {
var newColor = Math.floor(Math.random() * this.ballColors.length);
if (this.ballColor != newColor) {
this.ballColor = newColor;
break;
}
}
this.ballElem.style.backgroundColor = this.ballColors[this.ballColor];
},
change: function() {
ballObj.change();
this.changeBallColor();
},
move: function() {
ballObj.move({
left: 0, top: 0,
right: this.boxWidth,
bottom: this.boxHeight
});
this.setBallPos();
},
init: function() {
this.getBoxSize();
ballObj.init(
this.ballElem.offsetWidth / 2, // radius
this.boxWidth / 2, // x pos
this.boxHeight / 2 // y pos
);
this.setBallPos();
setInterval(() => this.move(), 50);
addEventListener("resize", () => this.getBoxSize());
}
};
ballPlayObj.init();
</script>