Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created February 7, 2013 16:40
Show Gist options
  • Select an option

  • Save codeincontext/4732237 to your computer and use it in GitHub Desktop.

Select an option

Save codeincontext/4732237 to your computer and use it in GitHub Desktop.
Running the same JS on client and server
var serverSide = (typeof module !== "undefined");
if (serverSide) {
var Canvas = require('canvas')
, Image = Canvas.Image
, fs = require('fs');
}
function HeroImage() {
var height = 620;
var width = 560;
var xOffset = 200;
var yOffset = 100;
this.updateFunction;
this.sex = "male";
this.stance = "standing";
this.attributes = {
skin: rand(5),
hairColour: rand(5),
hairStyle: rand(3),
top: rand(5),
bottom: rand(5),
boots: rand(5)
}
function rand(x){
return Math.floor((Math.random()*x)+0.5);
}
this.setAttribute = function(attribute, value) {
this.attributes[attribute] = value;
this.updateFunction && this.updateFunction();
}
this.loadSprites = function(callback) {
var spritesLoaded = 0;
var path = serverSide ? 'public' : '';
var onerror = function(err) { console.log('ERROR',err); };
var onload = function() {
if (++spritesLoaded == 2) callback && callback()
};
this.sprite = new Image();
this.hairSprite = new Image();
this.sprite.onload = this.hairSprite.onload = onload;
this.sprite.onerror = this.hairSprite.onerror = onerror;
this.sprite.src = path+'/images/'+this.sex+'-'+this.stance+'.png';
this.hairSprite.src = path+'/images/'+this.sex+'-hair.png';
}
this.drawPart = function(ctx, down, across) {
var partWidth = 200;
var partHeight = 400;
var x = across * partWidth;
var y = down * partHeight;
ctx.drawImage(this.sprite, x, y, partWidth, partHeight, xOffset, yOffset, partWidth, partHeight);
}
this.drawHair = function(ctx, down, across) {
var hairWidth = 150;
var hairHeight = 150;
var x = across * hairWidth;
var y = down * hairHeight;
ctx.drawImage(this.hairSprite, x, y, hairWidth, hairWidth, xOffset, yOffset, hairWidth, hairWidth);
}
this.drawOnContext = function(ctx) {
ctx.clearRect(0, 0, width, height);
this.drawPart(ctx, 0, this.attributes.skin);
this.drawPart(ctx, 1, this.attributes.top);
this.drawPart(ctx, 2, this.attributes.bottom);
this.drawHair(ctx, this.attributes.hairStyle, this.attributes.hairColour);
this.drawPart(ctx, 3, this.attributes.hair);
this.drawPart(ctx, 4, this.attributes.shoes);
this.drawPart(ctx, 5, this.attributes.accessory);
};
};
if (serverSide) {
module.exports = HeroImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment