Search code examples
canvaspositioning

canvas - can you set a coordinate as a new zero point to position elements relatively to?


I'm currently working on a little game in order to get familiar with the canvas thingy - now I've got a Menu class like this

function Menu(x,y,width,height,...,game){
    this.x      = x;
    this.y      = y;
    this.width  = width;
    this.height = height;
    // ...

    this.render = function(){
        game.stage.fillRect(this.x, this.y, this.width, this.height); // draw background
        // ...
        game.stage.fillText("MENU", this.x + 20, this.y + 10);
    }
}

is it possible set the this.x and the this.y as some kind of default value, so I don't have to write this.x + ... every time I want to position something within the menu?


Solution

  • Just translate your scene to the menu position (this.x, this.y) at the begining of menu drawing function. Don't forget to reset it afterwards.

    I assume game.stage is a canvas context object.

    game.stage.save();
    game.stage.translate(this.x, this.y);
    
    // now (0, 0) becomes (this.x, this.y)
    // ... some drawings
    
    game.stage.restore();