canvas drawing multiple objects onto screen. How to mirror some horizontally

Viewed 12

enter image description here

Currently drawing a bunch of little characters onto a canvas. Each human has its individual draw method which draws the image onto the canvas.

interface Follower{
  this.pos = {x: number, y: number};
  this.moveDir = {x: number, y:number};
  this.update = () => void // gets called on the update method which updates the position slightly
  this.draw = function() {
    ctx.imageSmoothingEnabled = false
    const followerImage = 
    canvasDetails.canvases.followersCanvas.assets['followerSpriteSheet']
    followerImage.width = this.width
    followerImage.height = this.height
    ctx.drawImage(followerImage, this.pos.x, this.pos.y, this.width, this.height);
}

Currently they just glide around the bounds of the grass however, I want them to face the direction they move in.

This can be easily determined by looking at the human.moveDir.x value. If it's negative, the sprite should be facing left. And if its positive, it should be facing right.

This is essentially what my code looks like:

const loop = () => {
  currentFollowers.forEach(follower => follower.update())
}

const draw = () => {
  currentFollowers.forEach(follower => follower.draw())
}

I figured this task would be super easy by just adding a condition within the draw method of each Follower... something like this:

follower.draw = function() {
    ctx.imageSmoothingEnabled = false
    const followerImage = canvasDetails.canvases.followersCanvas.assets['followerSpriteSheet']
    followerImage.width = this.width
    followerImage.height = this.height
    ctx.save()
    if (follower.moveDir.x < 0) { <-----
      ctx.scale(-1, 1)
    }
    ctx.restore()
    ctx.drawImage(followerImage, this.pos.x, this.pos.y, this.width, this.height);
}

But this doesnt work. When facing left, the image just disappears. I've tried a couple more things to no avail. Im potentially thinking about having a separate canvas layer that is mirrored by default and drawing the followers that are facing left there.

Would appreciate the help!

1 Answers

After fiddling around it some more, i got it working with this:

if (this.moveDir.x < 0) {
    ctx.save()

    ctx.setTransform(-1, 0, 0, 1,this.pos.x + this.width, this.pos.y);

    ctx.drawImage(followerImage, 0, 0)
    ctx.restore()
}
Related