您可以将坐标设置为新的零点以相对于元素进行定位吗?



我目前正在做一个小游戏,以熟悉画布的东西 - 现在我有一个这样的菜单类

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);
    }
}

是否可以将this.xthis.y设置为某种默认值,这样我就不必每次想在菜单中定位某些内容时都写this.x + ...

只需将您的场景转换为菜单绘制功能开头的菜单位置(this.x,this.y)。之后不要忘记重置它。

我假设game.stage是一个画布上下文对象。

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

最新更新