 |
|
|  |
| 자바스크립트 연습 예제 - 랜덤하게 움직이는 텍스트 만들기 |
|
|
 |
10년 전 |
<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>
//Moving Text의 생성자 함수
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에 추가
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> |
|
추천 : 488 |
추천
목록
|
|
|  |
|