Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Created October 4, 2012 18:06
Show Gist options
  • Save Shinpeim/3835340 to your computer and use it in GitHub Desktop.
Save Shinpeim/3835340 to your computer and use it in GitHub Desktop.
class Point{
x : number;
y : number;
constructor(x:number, y:number) {
this.x = x;
this.y = y;
}
}
class Size{
width : number;
height: number;
constructor(width:number, height:number) {
this.width = width;
this.height = height;
}
}
class Sprite{
position : Point;
size : Size;
image : HTMLImageElement;
canvas : HTMLCanvasElement;
isLoaded : bool;
constructor(canvas:HTMLCanvasElement, src:string, position:Point, size:Size){
var self = this;
this.canvas = canvas;
this.position = position;
this.size = size;
this.image = new Image();
this.image.src = src;
this.image.onload = function(){self.isLoaded = true};
}
moveY(length:number){
this.position.y += length;
}
moveX(length:number){
this.position.x += length;
}
draw(){
var ctx = this.canvas.getContext('2d');
ctx.drawImage(this.image, this.position.x, this.position.y, this.size.width, this.size.height);
}
}
function random(max:number){
return parseInt("" + (Math.random() * max));
}
class App{
excels : Sprite[];
canvas : HTMLCanvasElement;
constructor(){
this.canvas = <HTMLCanvasElement>document.getElementById("canvas");
var excel_size = 40;
var canvas_size = this.canvas.width;
var max_num = canvas_size - excel_size;
this.excels = [
new Sprite(this.canvas, "excel.png", new Point(random(max_num),random(max_num)), new Size(excel_size, excel_size)),
new Sprite(this.canvas, "excel.png", new Point(random(max_num),random(max_num)), new Size(excel_size, excel_size)),
new Sprite(this.canvas, "excel.png", new Point(random(max_num),random(max_num)), new Size(excel_size, excel_size)),
new Sprite(this.canvas, "excel.png", new Point(random(max_num),random(max_num)), new Size(excel_size, excel_size)),
];
}
isInitialized(){
for (var i = 0,l = this.excels.length; i < l; i++ ) {
var ex = this.excels[i];
if ( ! ex.isLoaded ) {
return false;
}
}
return true;
}
run(){
var self = this;
setInterval(function(){self.update()},1000 / 60);
}
update(){
if ( ! this.isInitialized() ) {
return;
}
var ctx = this.canvas.getContext('2d');
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (var i = 0,l = this.excels.length; i < l; i++ ) {
var ex = this.excels[i];
ex.moveY(random(3) - 1);
ex.moveX(random(3) - 1);
ex.draw();
}
}
}
onload = function() {
var app = new App();
app.run();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment