혼자 공부하는데 해결이 안돼서 질문드립니다.
조회수 470회
코드의 목적은 "알파벳이 아닌 1부터 20까지의 숫자를 랜덤하게 출력해서 애니메이션 실행하기" 입니다.
코드를 계속 수정하려고 하고 있는데, 도저히 답이 안보여서 질문드립니다.
우선 전체 코드입니다.
<!DOCTYPE html>
<html>
<head>
<script>
function nextRandomInteger(limit) {
return Math.round(Math.random() * limit);
}
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function randomAlphabet() {
return alphabet.charAt(nextRandomInteger(25));
}
function randomSpeed(maxSpeed) {
return Math.random() * maxSpeed - Math.random() * maxSpeed;
}
</script>
<script>
var canvasWidth = 700;
var canvasHeight = 400;
function MovingText() {
this.x = nextRandomInteger(canvasWidth);
this.y = nextRandomInteger(canvasHeight);
this.vx = randomSpeed(10);
this.vy = randomSpeed(10);
this.body = document.createElement('h1');
this.body.innerHTML = randomAlphabet();
this.body.style.position = 'absolute';
document.body.appendChild(this.body);
}
MovingText.prototype.move = function () {
if (this.x < 0 || this.x > canvasWidth) { this.vx *= -1; }
if (this.y < 0 || this.y > canvasHeight) { this.vy *= -1; }
this.x += this.vx;
this.y += this.vy;
this.body.style.left = this.x + 'px';
this.body.style.top = this.y + 'px';
};
</script>
<script>
window.onload = function () {
var movingTexts = [];
for (var i = 0; i < 100; i++) {
movingTexts.push(new MovingText());
}
setInterval(function () {
for (var i in movingTexts) {
movingTexts[i].move();
}
}, 1000 / 60);
};
</script>
</head>
<body>
</body>
</html>
이 코드를 실행하면
이런 식으로 글자가 막 난잡하게 날아다니는 애니메이션이 만들어집니다.
여기서 랜덤하게 알파벳을 생성하는 코드는
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function randomAlphabet() {
return alphabet.charAt(nextRandomInteger(25));
}
이것으로 보입니다.
처음에는 그냥 alphabet 변수 안에 있는 알파벳을 12345678910... 이런 식으로 적었는데, 이렇게 적으니까 1부터 9까지는 잘 출력됐는데, 10부터 20까지는 출력되지도 않았습니다. 아무래도 제가 두자리 수라고 적어 놓은 걸 프로그램이 이를 각각 한자리 수로 봐서 '10'이 아니라 '1' / '0' 이런 식으로 이해한 것 같습니다.
저는 여기서 숫자가
1 2 3 4 5 6 7 8 9 0 1 2 3 4...
이런 식으로 출력되는 것이 아니라
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15...
이런 식으로 출력되게 프로그램을 짜고 싶습니다.
그런데 해결책이 보이지 않아 질문드립니다.
댓글 입력