Skip to content

Instantly share code, notes, and snippets.

@wjx
Last active December 5, 2016 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjx/fb4ce795666a7c6e591c0f0b54e43658 to your computer and use it in GitHub Desktop.
Save wjx/fb4ce795666a7c6e591c0f0b54e43658 to your computer and use it in GitHub Desktop.
Implementation for book EloquentJavaScript chapter16 exercise "Precomputed mirroring"
var playerSprites = document.createElement("img");
var extraCanvas = document.createElement("canvas");
var extraCx = extraCanvas.getContext("2d");
playerSprites.src = "img/player.png";
playerSprites.addEventListener("load", function(event) {
var width = playerSprites.width;
var height = playerSprites.height;
extraCx.scale(-1, 1);
extraCx.translate(-width, 0);
extraCx.drawImage(playerSprites, 0, 0, width, height,
0, 0, width, height);
});
var playerXOverlap = 4;
CanvasDisplay.prototype.drawPlayer = function(x, y, width,
height) {
var sprite = 8, player = this.level.player;
width += playerXOverlap * 2;
x -= playerXOverlap;
if (player.speed.x != 0)
this.flipPlayer = player.speed.x < 0;
if (player.speed.y != 0)
sprite = 9;
else if (player.speed.x != 0)
sprite = Math.floor(this.animationTime * 12) % 8;
this.cx.save();
if (this.flipPlayer) {
this.cx.drawImage(extraCanvas,
(9 - sprite) * width, 0, width, height,
x, y, width, height);
} else {
this.cx.drawImage(playerSprites,
sprite * width, 0, width, height,
x, y, width, height);
}
this.cx.restore();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment