0

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Archade!</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div style="text-align: center;">
      <canvas id="gameCanvas"></canvas>
    </div>
    <script>
      var canvas;
      var canvasContext;
      window.onload = function () {
        console.log("Game working!");
        canvas = document.getElementById("gameCanvas");
        canvasContext = canvas.getContext("2d");
        canvasContext.fillStyle = "black";
        canvasContext.fillRect(0, 0, canvas.width, canvas.height);
        console.log("Loading red box");
        canvasContext.fillStyle = "red";
        canvasContext.fillRect(500, 500, 50, 25);
        console.log("Red box should be loaded!");
      };
    </script>
  </body>
</html>

This is my html code, [ in style.css i've just set width and height of the canvas ].

The black canvas is being displayed on the screen but the red box isn't displayed anywhere. The console log above and below the red rectangle is also working fine. Please help me fix this! I want the red rectangle to be displayed as well.

Thanks for your time :)

2 Answers2

0

From this reference - https://www.w3schools.com/tags/canvas_fill.asp

You can do the following:

  1. First draw the rectangle.
  2. Then, set the fillStyle.
  3. Then fill the rectangle.

Check the code below:

var canvas;
var canvasContext;
window.onload = function() {
  console.log("Game working!");
  canvas = document.getElementById("gameCanvas");
  canvasContext = canvas.getContext("2d");
  canvasContext.rect(0, 0, canvas.width, canvas.height);
  canvasContext.fillStyle = "black";

  canvasContext.fill();
  console.log("Loading red box");

  canvasContext.rect(500, 500, 50, 25);
  canvasContext.fillStyle = "red";
  canvasContext.fill();
  console.log("Red box should be loaded!");
};
<div style="text-align: center;">
  <canvas id="gameCanvas"></canvas>
</div>
jaimish11
  • 536
  • 4
  • 15
  • While the above code does work, it would be great if someone could explain why the code given in the question does not work. – jaimish11 Aug 02 '20 at 11:06
0

Setting the canvas size in css might not be enough. Try also setting the width/height attributes of the canvas element.

For example:

canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

I think the red rectangle isn't displayed because it's position exceeds the default size of a canvas.

1polygon
  • 81
  • 1
  • 2