On my canvas I have two rectangles drawn. The first with a larger height and second with a smaller height. Here is a screen shot:
In my code I represent them with classes and then instantiate them: Here is how I do it:
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);
What I want to do is now make the pink rectangle appear in place of black and black in place of pink. Can anyone tell me how to do that?
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();
You can try swap location of obj1 and obj2:! ex:
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;
after this, call update
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.