Functions 2 test review

Hello. Can you take a look at this code and see if it needs some tinkering?

Thanks a lot.

    let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
    let para = document.createElement('p');

    // Add your code here

    let canvas = document.querySelector('canvas');
    let ctx = canvas.getContext('2d');

    let x = 50;
    let y = 60;
    let width = 100;
    let height = 75;
    let color = 'blue';

    // Add your code here

    function rectangle() {
      if (canvas.getContext) {
        let ctx = canvas.getContext('2d');
        ctx.clearRect(x, y, width, height);
        ctx.fillRect(x, y, canvas.width, canvas.height);
        ctx.fillStyle = 'blue';


    // Don't edit the code below here!

    const section = document.querySelector('section');

Hi @jag!

You’ve got this code a bit confused. Let me give you a few points, then you can try again:

  1. You don’t really need the if statement inside the rectangle() function, or the let ctx = canvas.getContext('2d'); line — the canvas and ctx variables are already initialized at the top of the code.
  2. The rectangle() function should take the variables as input arguments.
  3. When you use clearRect() you need to set the width and height as canvas.width and canvas.height; at the moment you are clearing a really small part of the canvas each time.
  4. Conversely, fillRect() needs to use width and height for the width and height :wink:
  5. You need to set fillStyle() before fillRect(), otherwise the rectangle won’t adopt the color.

If you still find yourself stuck, you could check out our answer:

Hi Chris

Many thanks for the help. I scrapped my code and put in the answer just to see what would happen. My code actually showed the blue square, while this one didn’t…

function rectangle(x, y, width, height, color) {
        ctx.fillStyle = 'white';
        ct.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = color;
        ctx.fillRect(x, y, width, height);

    rectangle(x, y, width, height, color);

That’s because you’ve introduced a typo on the third line down. ct > ctx

:woozy_face: thanks for that, works normal now