Skip to content

Instantly share code, notes, and snippets.

@eltonsantos
Created January 18, 2017 07:47
Show Gist options
  • Save eltonsantos/3f3d2c12d36cdd13264e95beb0cd5264 to your computer and use it in GitHub Desktop.
Save eltonsantos/3f3d2c12d36cdd13264e95beb0cd5264 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Testing sprites</title>
<script>
// SPRITESHEET
function Spritesheet(context, imagem, linhas, colunas) {
this.context = context;
this.imagem = imagem;
this.numLinhas = linhas;
this.numColunas = colunas;
this.intervalo = 0;
this.linha = 0;
this.coluna = 0;
}
Spritesheet.prototype = {
proximoQuadro: function () {
var agora = new Date().getTime();
if (!this.ultimoTempo) this.ultimoTempo = agora;
if (agora - this.ultimoTempo < this.intervalo)
return;
if (this.coluna < this.numColunas - 1) {
this.coluna++;
}
else
this.coluna = 0;
this.ultimoTempo = agora;
},
desenhar: function (x, y) {
var largura = this.imagem.width / this.numColunas;
var altura = this.imagem.height / this.numLinhas;
this.context.drawImage(this.imagem, largura*this.coluna, altura*this.linha, largura, altura, x, y, largura, altura);
}
}
</script>
</head>
<body>
<canvas id="canvas" height="500" width="500"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = 0;
var y = 0;
var background = new Image();
background.src = "background.png";
background.onload = function(){
context.drawImage(background, 0, 0);
};
var lizard_img = new Image();
lizard_img.src = "lizard.png";
var sheet = new Spritesheet(context, lizard_img, 6, 9);
sheet.intervalo = 60;
sheet.linha = 5;
lizard_img.onload = gameLoop;
var disco_img = new Image();
disco_img.src = "disco.png";
var sheetDisco = new Spritesheet(context, disco_img, 6, 1);
sheetDisco.intervalo = 60;
sheetDisco.linha = 0;
disco_img.onload = gameLoopDisco;
var dokuro_img = new Image();
dokuro_img.src = "dokuro.png";
var sheetDokuro = new Spritesheet(context, dokuro_img, 6, 4);
sheetDokuro.intervalo = 60;
sheetDokuro.linha = 2;
dokuro_img.onload = gameLoopDokuro;
function gameLoop () {
//context.clearRect(0, 0, context.canvas.width, context.canvas.height);
sheet.proximoQuadro();
sheet.desenhar(200, 200);
requestAnimationFrame(gameLoop);
}
function gameLoopDisco () {
//context.clearRect(0, 0, context.canvas.width, context.canvas.height);
sheetDisco.proximoQuadro();
sheetDisco.desenhar(300, 100);
requestAnimationFrame(gameLoopDisco);
}
function gameLoopDokuro () {
//context.clearRect(0, 0, context.canvas.width, context.canvas.height);
sheetDokuro.proximoQuadro();
sheetDokuro.desenhar(100, 300);
requestAnimationFrame(gameLoopDokuro);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment