skip to Main Content

I’m trying to make a pixelated image by hand, but the editor im using does not allow copy and pasting, which means I have to type everything by hand, so defining a new rectangle each time I wanna use it is too much work.

What I tried was:

const grey = new Rectangle(10, 10);
grey.setPosition (100, 400);
grey.setColor ("#686968");
add (grey);
grey. setPosition (110, 400);
grey.setColor("#686968");
add (grey);

But instead of adding another grey square, it just moved the first one.

I also looked online and did not find anything that helped.

2

Answers


  1. Create a function that makes the Rectangle for you, based on some parameters:

    function getColoredRectangle(color, x, y, width = 10, height = 10, ) {
        const rect = new Rectangle(width, height);
        rect.setPosition(x, y);
        rect.setColor(color);
        return rect;
    }
    
    add(getColoredRectangle("#686968", 100, 400))
    add(getColoredRectangle("#123456", 110, 400))
    
    Login or Signup to reply.
  2. In Javascript, variable are passed par reference to function. So when you call the add twice, it calls with the same object.

    If you want to copy your rectangle, you need to create a new object from the first one and pass this new object to the add function, the second time.

    const grey = new Rectangle(10, 10);
    grey.setPosition (100, 400);
    grey.setColor ("#686968");
    add (grey);
    
    const newRectangle = /** create a new rectangle from gray **/
    newRectangle. setPosition (110, 400);
    newRectangle.setColor("#686968");
    
    add (newRectangle);
    

    We don’t know anything about the Rectangle class, so we cannot help you on the specific of how to create the new rectangle, but this should give you an idea of what to do.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search