Skip to content

Instantly share code, notes, and snippets.

@vasco3
Created October 3, 2013 01:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasco3/6803281 to your computer and use it in GitHub Desktop.
Save vasco3/6803281 to your computer and use it in GitHub Desktop.
Playing with OOP JS to draw an image in HTML Canvas
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var imgs = {
"spaceShip" : document.getElementById("space"),
"scream" : document.getElementById("scream")
}
function Scene(context, width, height, images){
this.context = context;
this.width = width;
this.height = height;
this.images = images;
this.actors = [];
}
Scene.prototype.register = function(actor){
this.actors.push(actor);
}
Scene.prototype.unregister = function(actor){
var i = this.actors.indexOf(actor);
if (i >= 0) {
this.actors.splice(i, 1);
}
};
Scene.prototype.draw = function() {
this.context.clearRect(0, 0, this.width, this.height);
for (var a = this.actors, i = 0, n = a.length; i < n; i++){
a[i].draw();
}
}
function Actor(scene, x, y){
this.scene = scene;
this.x = x;
this.y = y;
this.actorID = ++Actor.nextID;
scene.register(this);
}
Actor.nextID = 0;
Actor.prototype.moveTo = function(x, y){
this.x = x;
this.y = y;
this.scene.draw();
};
Actor.prototype.exit = function() {
this.scene.unregister(this);
this.scene.draw();
};
Actor.prototype.draw = function() {
var image = this.scene.images[this.type];
this.scene.context.drawImage(image, this.x, this.y);
};
Actor.prototype.width = function() {
return this.scene.images[this.type].width;
};
Actor.prototype.height = function() {
return this.scene.images[this.type].height;
};
function Spaceship(scene, x, y) {
Actor.call(this, scene, x, y);
this.points = 0;
}
Spaceship.prototype = Object.create(Actor.prototype);
Spaceship.prototype.type = "spaceShip";
Spaceship.prototype.scorePoint = function() {
this.points++;
};
Spaceship.prototype.left = function() {
this.moveTo(Math.max(this.x - 10, 0), this.y);
};
Spaceship.prototype.right = function(){
var maxWidth = this.scene.width - this.width();
this.moveTo(Math.min(this.x + 10, maxWidth), this.y);
};
function Alien(scene, x, y, direction, speed, strength) {
Actor.call(this, scene, x, y);
this.direction = direction;
this.speed = speed;
this.strength = strength;
this.damage = 0;
this.alienID = ++Alien.nextID;
}
Alien.prototype.type = "scream";
Alien.nextID = 0;
var scene1 = new Scene(ctx, 300, 300, imgs);
var spaceship1 = new Spaceship(scene1, 40, 40);
scene1.draw();
console.log(scene1.actors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment