Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.