javascriptcanvashtml5-canvasconditional-statementsdrawimage

conditional context.drawImage() function


I have a context.drawImage() function inside a draw function of a class.

When I pass static values it works just fine: context.drawImage(this.image, this.position.x -12, this.position.y -12)

But what I want is a conditional passing of values: context.drawImage( this.scared ? this.image, this.position.x -12, this.position.y -12 : this.imageScared, this.position.x -12, this.position.y -12 ).

And this is not working.

class Ghost {
  static speed = 2;
  constructor({position, velocity, color = 'red', image, imageScared}) {
    this.position = position;
    this.velocity = velocity;
    this.radius = 15 * 0.8;
    this.color = color;
    this.prevCollisions = []
    this.speed = 2;
    this.scared = false;
    this.image = image;
    this.imageScared = imageScared;
  }
  draw() {
    context.beginPath();
context.arc(this.position.x,this.position.y, this.radius, 0, Math.PI * 2)
context.fillStyle = this.scared ? 'blue' : this.color;
context.fill();
context.closePath();
context.drawImage( if (this.scared) { this.image, this.position.x -12, this.position.y -12 } else { this.imageScared, this.position.x -12, this.position.y -12 } )
  }
  update() {
    this.draw();
    this.position.x += this.velocity.x;
    this.position.y += this.velocity.y;
  }
}


Solution

  • Looks like you used the ternary operator and then wrote an if statement as an argument? Anyways, you can use ternary in your context.drawImage statement.

    context.drawImage( this.scared ? this.image : this.imageScared, this.position.x -12, this.position.y -12 );

        class Ghost {
          static speed = 2;
          constructor({position, velocity, color = 'red', image, imageScared}) {
            this.position = position;
            this.velocity = velocity;
            this.radius = 15 * 0.8;
            this.color = color;
            this.prevCollisions = []
            this.speed = 2;
            this.scared = false;
            this.image = image;
            this.imageScared = imageScared;
          }
          draw() {
            context.beginPath();
            context.arc(this.position.x,this.position.y, this.radius, 0, Math.PI * 2)
            context.fillStyle = this.scared ? 'blue' : this.color;
            context.fill();
            context.closePath();
            context.drawImage( this.scared ? this.image : this.imageScared, this.position.x -12, this.position.y -12 );
          }
          update() {
            this.draw();
            this.position.x += this.velocity.x;
            this.position.y += this.velocity.y;
          }
        }