Can't draw on canvas .What could be the problem?

I am trying to draw something very basic to my canvas but its not drawing anything neither showing any errors to fix. what could be the issue here ?

Here's my code :

I also tried moving the js code to an external js file but did't work.

<body>
<canvas
  id="myCanvas"
  width="800"
  height="500"
  style="border:1px solid #474747;"
></canvas>

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect = (10, 100, 15, 400);
</script>

2 answers

  • answered 2019-09-10 02:13 Nick Parsons

    Your issue is with:

    ctx.fillRect = (10, 100, 15, 400);
    

    .fillRect() is a method which takes a x, y, width, height as it parameters, so you need to call it like so:

    ctx.fillRect(10, 100, 15, 400);
    

    See example below:

    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(10, 100, 15, 400);
    <canvas id="myCanvas" width="800" height="500" style="border:1px solid #474747;"></canvas>

  • answered 2019-09-10 02:16 symlink

    ctx.fillRect = (10, 100, 15, 400); <-- fillRect() is a function, you're using it as an expression.

      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#FF0000";
      ctx.fillRect(10, 100, 15, 400);
    <canvas
      id="myCanvas"
      width="800"
      height="500"
      style="border:1px solid #474747;"
    ></canvas>