繁体   English   中英

如何交换 HTML canvas 中的两个 canvas 元素?

[英]How to swap two canvas elements in HTML canvas?

在我的 canvas 上,我绘制了两个矩形。 第一个高度较大,第二个高度较小。 这是一个屏幕截图: 在此处输入图像描述

在我的代码中,我用类来表示它们,然后实例化它们:我是这样做的:

class Rectangle {
    constructor(x, y, width, height, color, value) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.color = color;
        this.value = value;
    }

    // draw function of this rectance will let it appear on the screen;

    draw() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height , this.color, this.value);
    }

    // the update function will swap the rectangle's property and redraw them again

    
    update(obj1, obj2) {
        var temp; 
        // saving the values of the first rectancgle in the temp variables

        for(var key in obj1) {
            this.temp = this.obj1[key];
            this.obj1[key] = this.obj2[key];
            this.obj2[key] = this.temp;
        }

        this.obj1.draw();
        this.obj2.draw();        
    }


}
var rect2 = new Rectangle(100, y-20, 50, 25, "pink", 40 );
rect2.draw();

var rect1 = new Rectangle(160, y, 50, 5, "black", 20);
rect1.draw();


rect1.update(rect1, rect2);

我现在要做的是让粉红色矩形代替黑色和黑色代替粉红色。 谁能告诉我该怎么做?

class Rectangle {
    constructor(x, y, width, height, color, value) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.color = color;
        this.value = value;
    }

    // draw function of this rectance will let it appear on the screen;

    draw() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height , this.color, this.value);
    }

    reposition(x,y) {    
        this.x = x;
        this.y = y;
    }

}
var rect2 = new Rectangle(100, y-20, 50, 25, "pink", 40 );
rect2.draw();

var rect1 = new Rectangle(160, y, 50, 5, "black", 20);
rect1.draw();

// do this – after some wait, click or however you like to trigger it
let buffer_x = rect1.x, buffer_y = rect1.y;
rect1.reposition(rect2.x,rect2.y);
rect2.reposition(buffer_x,buffer_y);
rect1.draw();
rect2.draw();

您可以尝试交换 obj1 和 obj2 的位置:! 前任:

var x1 = this.obj1.x, y1 = this.obj1.y;
this.obj1.x = this.obj2.x;
this.obj1.y = this.obj2.y;
this.obj2.x = x1;
this.obj2.y = y1;

在此之后,调用更新

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM