Search code examples
javascriptcanvascanvasjs

Why my rectangles don't appear in my canvas javascript?


I don't know what's missing in my js code, but the rectangles don't appear, what am I missing? I have been having this problem for some time now

"use strict";
let ctx;


function setup() {
  let canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  
  figures();
}

function figures(){
    ctx.fillStyle = "red";
  ctx.fillRect(50, 50, 150, 75);
    ctx.fillStyle = "red";
  ctx.fillRect(200, 200, 60, 100);
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>rectangles</title>
    <link href="javascript.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="script.js"></script>
     <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>
  </body>
</html>


Solution

  • you need to place your script tag as the last tag in your body , the browser renders the page as it parses it from top to bottom. This means that when it reaches the script part at the end of the body tag, your HTML should be loaded, so the elements used by your scripts will most likely be present , and also you need to call the setup function in your javascript file html file

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>rectangles</title>
        <link href="javascript.css" rel="stylesheet" type="text/css" />
      </head>
      <body>
      <script src="script.js"></script>  
         <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>
     
    </body>
    </html>
    
    

    javascript file

    "use strict";
    let ctx;
    
    
    function setup() {
      let canvas = document.getElementById("myCanvas");
      ctx = canvas.getContext("2d");
      
      figures();
    }
    
    function figures(){
        ctx.fillStyle = "red";
      ctx.fillRect(50, 50, 150, 75);
        ctx.fillStyle = "red";
      ctx.fillRect(200, 200, 60, 100);
    }
    
    setup();