■ canvas 엘리먼트에서 setInterval 함수를 사용해 애니메이션을 만드는 방법을 보여준다.
▶ test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script language="javascript"> var canvas; var context; var rainArray; var count = 100; function rain() { var xPosition; var yPosition; var speed; var color; } function run() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); for(var i = 0; i < this.count; i++) { this.context.fillStyle = this.rainArray[i].color; this.context.fillRect(this.rainArray[i].xPosition, this.rainArray[i].yPosition, 10, 10); this.rainArray[i].yPosition += this.rainArray[i].speed; if(this.rainArray[i].yPosition > this.canvas.height) { this.rainArray[i].yPosition = 0; } } } function onLoad() { this.canvas = document.getElementById('canvas'); this.context = this.canvas.getContext('2d'); this.rainArray = []; for(var i = 0; i < this.count; i++) { var xPosition = Math.floor(Math.random() * this.canvas.width); var yPosition = 0; var speed = Math.random() * 2; this.rainArray[i] = new rain(); this.rainArray[i].xPosition = xPosition; this.rainArray[i].yPosition = yPosition; this.rainArray[i].speed = speed; this.rainArray[i].color = 'rgb(' + Math.ceil(Math.random() * 255) + ',' + Math.ceil(Math.random() * 255) + ',' + Math.ceil(Math.random() * 255) + ')'; } setInterval(run, 10); } </script> </head> <body onload="onLoad();"> <canvas id="canvas" width="400" height="400" /> </body> </html> |