Canvas 个矩形具有相同的 x 和 y,但不应该

Canvas rectangles are having the same x and y but shouldn't be

嘿,我正在制作一个 HTML5 游戏,我想在 canvas 上制作按钮。

     Button = function(text, x, y, width, height){
            self.x = x;
            self.y = y;
            self.width = width;
            self.height = height;

            self.createButton = function(){
                ctx.save();
                ctx.fillStyle = "yellow";
                ctx.fillRect(self.x, self.y, self.width, self.height);

                ctx.fillStyle = "black";
                ctx.font = '30px Arial';
                ctx.fillText(self.text, self.x, self.y + (self.height / 2));

                ctx.restore();
            }

        self.createButton();

        return self;
    }

这是我制作按钮的功能,我在代码的其他地方制作了两个按钮 -

       var button1 = Button('Button 1', WIDTH / 2, HEIGHT / 2, 200, 40);

        var button2 = Button('Button 2', WIDTH / 2, (HEIGHT / 2) + 50, 200, 40);

        console.log('button1 x: ', button1.x);
        console.log('button1 y: ', button1.y);


        console.log('button2 x: ', button2.x);
        console.log('button2 y: ', button2.y);

按钮最终是单独绘制的。但是当我在代码中调出 x 和 ys 时,它们完全相同。

The buttons wind up being drawn separately.. but when I console out the x and ys in the code they're both exactly the same.

那是因为您将值分配给 全局 变量 self, which already exists, and refers to the window object.

所以您并没有像您想象的那样在这里使用单独的变量,而是使用一个相同的变量——每次都覆盖它的 x、y、... 属性。

将此作为第一行插入到您的函数中,以创建一个 local 变量并将其初始化为一个空对象:

var self = {};

如果不将其初始化为(空)对象,您会收到类似 Uncaught TypeError: Cannot set property 'x' of undefined 的错误消息。你没有用你的代码得到这个的唯一原因是因为 self 之前已经是一个现有的对象。

但是为了避免混淆,最好选择一个不同的变量名作为开头——使用 _self 来代替在对象中存储对自身的引用是很常见的。